【问题标题】:Replacing Image Source Value With a PHP Variable Based on Device Width用基于设备宽度的 PHP 变量替换图像源值
【发布时间】:2014-06-26 07:15:42
【问题描述】:

我希望能够将 img 的 src 值与 PHP 中创建的变量交换。

我目前正在使用 javascript 来确定设备宽度。这发生在包含 Wordpress 循环的 .php 文件中。在识别设备宽度后,我想相应地更改 img 的 src 值。

我可以使用这个 JS 函数成功检索 PHP 变量,但是只有在循环中编写该函数时,并且众所周知,这将复制每个帖子的函数并导致错误。

我需要能够在循环外计算这些给定的 PHP 变量,然后将它们注入到循环内的 img src 值中。

我知道这段代码中的错误可能比我要解决的错误更多!我已经为此工作了一段时间,这个特定的问题已经变得非常令人不安。提前致谢。

当前使用的代码:

<?php query_posts( array ( 'home' => 'WordPress Themes', 'orderby' => 'rand', 'posts_per_page' => -1 ) ); ?>
<?php while ( have_posts() ) : the_post(); ?>
  <script>
    function getImagePath(){
      if (window.matchMedia('(max-device-width: 1920px)').matches) {
        var theSizedImage = <?php the_field('desktop_image'); ?>
      }if (window.matchMedia('(max-device-width: 1280px)').matches) {
        var theSizedImage = <?php the_field('tablet_image'); ?>
      }if (window.matchMedia('(max-device-width: 600px)').matches) {
        var theSizedImage = <?php the_field('mobile_image'); ?>
      }
      return theSizedImage;
    } 
   </script>
   <img src="pixel.gif" onload="this.onload=null; this.src=getImagePath();"  />
<?php endwhile;
wp_reset_query();
?>

【问题讨论】:

    标签: php jquery wordpress loops


    【解决方案1】:

    因此,经过进一步的修补,我能够想出一个解决方案。 这确实有效,但是我想知道是否有更优雅的解决方案。 您会注意到,随着我改进页面并处理错误,我的查询略有变化。上述代码的主要问题是图像 URL 的变量只定义了一次。我在下面提供的解决方案将为循环中的每个帖子重新运行。

    <?php query_posts( array ( 'category__not_in' => array( 1, 4, 5, 6, 7 ), 'orderby' => 'rand', 'posts_per_page' => -1 ) ); ?>
    <?php while ( have_posts() ) : the_post(); ?>
        <script>
           if (screen.width <= 1920) {document.write("<img src='<?php the_field('desktop_image');?>'   />");}
           if (screen.width <= 1280) {document.write("<img src='<?php the_field('tablet_image');?>'  />");}
           if (screen.width <= 600) {document.write("<img src='<?php the_field('mobile_image');?>'  />");}
           if (screen.width > 1920){document.write("<img src='<?php the_field('full_resolution');?>'  />");}
        </script>
    <?php endwhile;
    wp_reset_query();
    ?>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-30
      • 2013-07-30
      • 2020-11-14
      • 2013-06-15
      • 1970-01-01
      • 2017-10-15
      • 1970-01-01
      • 2019-09-01
      相关资源
      最近更新 更多