php - 使用基于设备宽度的 PHP 变量替换图像源值

标签 php jquery wordpress loops

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

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

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

我需要能够在循环外计算这些给定的 PHP 变量,然后将它们注入(inject)到循环内的 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();
?>

最佳答案

经过进一步的修改,我找到了一个解决方案。 这实际上确实有效,但我想知道是否有更优雅的解决方案。 您会注意到,随着我改进页面并解决错误,我的查询发生了轻微变化。上面代码的主要问题是图像 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();
?>

关于php - 使用基于设备宽度的 PHP 变量替换图像源值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24424526/

相关文章:

javascript - 我无法调用我的 jQuery 函数

javascript - 将 Middleman 数据文件夹中的 JSON 文件解析为 Javascript 文件作为数组

wordpress - Noob问题:Wordpress循环

php - 简单的 mod_rewrite 问题

php - 如何加密和解密 PHP 字符串?

javascript - Onchange 下拉值查询响应。表 - 使用 php , mysql , ajax , jquery

javascript - 测试是否缺少 .data() 结果

php - 是否有最佳实践方法来近似 WordPress 插件中的命名空间 PHP?

php - 在我的 sidebar.php 文件中将西里尔文编码为 UTF-8,该网站中断

php - 如何在 HTML 中输出 JSON 数组