在PHP中使用jQuery更改滚动图像不工作



我有一个php网站,我有一个道路的背景图像,一个字符的2个图像,当用户滚动时,我希望图像改变,直到部分结束,这样它看起来像字符正在移动。

我用jQuery编写了以下代码:

$(document).ready(function() {
$(window).on("scroll", function() {
console.log($(this).scrollTop())
<?php for($i=30;$i<=2500;$i++){ ?>
if($(this).scrollTop() >= <?=$i?>){
// set to new image
$(".bgimg img").attr("src","char1.png");
} else {
//back to default
$(".bgimg img").attr("src","char2.png");
}
<?php } ?>
})
})
.bgimg {
background-image: url('road.png');
height: 2500px;
background-size:cover;
width:50%

}
<div class="container" style="text-align: -webkit-center;">
<div class="row">
<p>This is a test </p>
</div>
<div class="row bgimg" >
<img src="char1.png" id="chara">
</div>
</div>

但是不起作用。谁能告诉我出了什么事?

Thanks in advance

我不知道这是否能回答你的问题,因为我不确定我是否理解你想要的,但这里有一些例子可能能帮助你(没有PHP循环)

<script>
$(function(){   
$(window).on("scroll", function() {
if($(this).scrollTop()>30)  $(".bgimg img").attr("src","char2.png");
else $(".bgimg img").attr("src","char1.png");
});
}); 
</script>

使用上面的脚本图像变化的阈值为30

--------------------------------------------------------------------------------------------------------

下面脚本随着用户"滚动",图像会交替变化。页面。

使用以下HTML代码

<div id="characterDiv"><img id="characterImage" src="char1.png"></div>
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim 
With a long text page to have a high enough window
</p>

使用这个CSS

<style type="text/css">
html { font-family:Arial; font-size: 0.9em; }
p { width: 50%; text-align: justify; }
#characterDiv {
position: fixed;
right: 50%;
top: 50%;
width: 8em;
margin-top: -2.5em;
}
</style>

和这个JQuery脚本(没有PHP循环,但有数学)

<script>
$(function(){   
$(window).on("scroll", function() {

let pitch = 150;

// Display for Test
console.log($(this).scrollTop()+' -> '+(Math.round($(this).scrollTop()/pitch))%2);

// This calculation gives alternately 0 or 1
if((Math.round($(this).scrollTop()/pitch))%2==0)    $("#characterImage").attr("src","char2.png");
else $("#characterImage").attr("src","char1.png");

});
}); 
</script>

最新更新