将 PHP 数据拉入 JS 动态改变屏幕宽度的 BG 图片

Pulling PHP data into JS to dynamically change BG image on screen width

在我的 WP 模板中,我在 Repeater[=65] 中创建了两个 子字段 =] bg imgs 的自定义字段:

  1. 大型设备和桌面背景
  2. 移动背景

在我的 content-section.php 模板部分,我创建了一个循环并成功地将 get_sub_field('background_image'); 作为背景图像注入。我想在宽度为 < 768 时将 bg-img 动态更改为 mobile。我知道您必须使用 wp_localize_script() 等将 php 数据传递给 js。

我试过的:

  1. content-section.php
  2. 中为 get_sub_field('mobile_background_image'); 设置变量
  3. 使用 AFC 函数的不同变体在 functions.php 中拉取 bg 数据:the_field('mobile_background_image')get_sub_field('mobile_background_image')the_sub_field('mobile_background_image'); 但我什至没有看到任何拉取的数据console.log() var,我得到的最多是null
  4. 写我的 .each() 多种方式:

    // Attempt #1
    $('.bg-img').each(function() {
    
      if($(window).width() < 768) {
        var bgUrl = 'url("' + php_vars.mobile_bg + '") center center no-repeat)'
        var style = {
            'background': bgUrl,
            'background-size': 'cover'
        }
        $('.bg-img').css(style);
      }
    
    }); 
    
    // Attempt #2
    if($(window).width() < 768) {
    
      $('.bg-img').each(function() {
        var bgUrl = 'url("' + php_vars.mobile_bg + '") center center no-repeat)'
        var style = {
            'background': bgUrl,
            'background-size': 'cover'
        }
    
        $('.bg-img').css(style);
      });   
    
    }
    

还有 $('.bg-img').css(style); 完全在函数之外的变体。

问题: 出于某种原因,我在检查时没有看到任何变化,也没有看到任何控制台错误。我怎样才能正确地提取 sub_field 数据并将其传递到我的 functions.php 和我的 scripts.js 一旦数据被拉出并设置在 var 中,我当前的函数就使用 .each() if(); 等...正确吗?

内容-section.php

<?php if( have_rows('section_content') ): ?>
    <?php while( have_rows('section_content') ): the_row(); 
        $sectionBG = get_sub_field('background_image');
        $sectionContent = get_sub_field('section_text');
    ?>
        <?php if( $sectionBG ): ?>
            <div style="background: url('<?php echo $sectionBG ?>') center center no-repeat; background-size: cover;" class="full-height v-center-content bg-img">
        <?php endif; ?>
                <div class="container animation-element">
                    <div class="row">
                        <?php if(get_row_index() % 2 == 0) : ?>
                            <div class="col-12 col-md-6 offset-md-6 col-xl-5 offset-xl-7">
                        <?php else : ?>
                            <div class="col-12 col-md-6 col-xl-5">
                        <?php endif; ?> 
                            <div class="section-content">
                                <?php echo $sectionContent ?>
                            </div>
                        </div>
                    </div>
                </div>
        <?php if( $sectionBG ): ?>  
            </div>
        <?php endif; ?>
    <?php endwhile; ?>
<?php endif; ?>

Function.php

wp_enqueue_script('main-js', get_template_directory_uri() . '/js/script.js', array('jquery'), '', true);

wp_localize_script('main-js', 'php_vars', array(
    'mobile_bg' =>  get_sub_field('mobile_background_image')
));
}

Script.js

$('.bg-img').each(function() {

    if($(window).width() < 768) {

        var bgUrl = 'url("' + php_vars.mobile_bg + '") center center no-repeat)'
        var style = {
            'background': bgUrl,
            'background-size': 'cover'
        }

        $('.bg-img').css(style);
    }

}); 
$(window).on('resize', function () {
   if($(this).width() < 768)
   {
     ('.bg-img').each(function() {
        var bgUrl = 'url("' + php_vars.mobile_bg + '") center center no-repeat)'
        var style = {'background': bgUrl,
                     'background-size': 'cover'};
        $(this).css(style);
      });
    }
});

这就是CSS媒体查询的作用。 在你的主要风格 sheet 你会

background-image: url('pic1.jpg');

在您的手机 css 文件中,您将拥有

background-image: url('pic2.jpg');

在你的html中你会

<link rel="stylesheet" href="style.css" type="text/css">
<link rel="stylesheet" href='mobile.css" type="text/css" media="only screen and (max-device-width:768px)">

这个问题可能很老 - 但你可以只安装 mobble 插件 - 它会告诉你页面上的设备类型 - 它还为正文添加了 class。

然后你可以简单地使用插件的核心功能 -

<?php
//is_handheld(); // any handheld device (phone, tablet, Nintendo)
//is_mobile(); // any type of mobile phone (iPhone, Android, etc)
//is_tablet(); // any tablet device
//is_ios(); // any Apple device (iPhone, iPad, iPod)
/*is_iphone();
//is_ipad();
//is_ipod();
//is_android();
//is_blackberry();
//is_opera_mobile();
//is_symbian();
//is_kindle();
//is_windows_mobile();
//is_motorola();
//is_samsung();
//is_samsung_tablet();
//is_sony_ericsson();
//is_nintendo(); */

if(is_mobile()) {
    $bgURL = get_sub_field("your mobile image here"); 
} else {
    $bgURL = get_sub_field("your desktop image here");
}

阅读有关插件功能的更多信息并在此处下载:https://wordpress.org/plugins/mobble/

经过多次修改,我找到了一个解决方案,允许我从我的函数 php 中动态提取转发器字段中的 ACF 数据并在我的 script.js

中使用

问题是我试图在没有 运行 has_rows 循环的情况下提取 get_sub_field() 数据,因此我没有收到任何数据。

已更新functions.php

$php_vars = array(
    'ajaxurl' => admin_url( 'admin-ajax.php' ),
    'root_dir'  =>  get_template_directory_uri()
);

if (have_rows('section_content')) :
    while (have_rows('section_content')) : the_row();

        $mobile_url[] = get_sub_field('mobile_background_image');

        $php_vars['mobile_bg'] = $mobile_url;
    endwhile;
endif;

print_r($php_vars);

wp_localize_script('main-js', 'php_vars', $php_vars);

在我的 functions.php 中,我创建了一个 have_loop- more info here - 检查页面上是否有转发器字段,如果有,请设置移动图像 url(s) 作为一个数组。之后,我创建了一个多维数组并将其添加到我的 $php_vars


已更新script.js

if ($(window).width() < 768) {

    var bgIMG = php_vars.mobile_bg;
    var i;

    console.log(bgIMG);

    for ( i = 0; i < bgIMG.length; i++) {
        $('.bg-img').attr('style', 'background: url("'+ bgIMG[i] +'") center center no-repeat; background-size: cover;');
    }

} 

在成功测试 url(s) 通过 print_r($php_vars); 存储为数组后,我能够将该数据调用到我的脚本中并将其存储到 var bgIMG.使用 console.log(bgIMG) 测试数据是否仍然完好无损,我创建了一个 for 循环以将数据添加到我的后台 url 并递增。


这是我想出的似乎有效的解决方案。如果有人有更好的解决方案或建议来改进这一点,我会洗耳恭听。