【发布时间】: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