老实说,我对JQuery很陌生,并且仍在努力蒙混过关。 话虽如此,我正在尝试创建一个简单的视差效果,但我无法完全让它工作。每当我更改数据速度属性时,它都会影响同一类的所有 Div,而不仅仅是它所在的 Div。因此,在下面的示例中,虽然 2 个div 应该以不同的速度滚动,但它们以与第一个div 完全相同的速度 (2) 滚动。
我的HTML是:
<div class="parallax" id="content1" data-speed="2">
Content
</div>
<div class="parallax" id="content2" data-speed="3">
Content 2
</div>
我的Jquery是:
jQuery(function( $ ){
// Enable parallax and fade effects on homepage sections
$(window).scroll(function(speed){
scrolltop = $(window).scrollTop()
scrollwindow = scrolltop + $(window).height();
speed = $(".parallax").data("speed")
$(".parallax").css("backgroundPosition", "50% " + -(scrolltop*speed) + "px");
});
});
我很确定这只是我不熟悉 JQuery 及其工作原理的情况......有人可以帮助我吗?
谢谢!
您的问题是由于以下行造成的:
speed = $(".parallax").data("speed")
$(".parallax").css("backgroundPosition", "50% " + -(scrolltop*speed) + "px");
$(".parallax")
选择所有具有 class="parallax"
的元素,但.data("speed")
只会提取集合中第一个元素的值。
然后,将该值应用于第二行中的所有$(".parallax")
元素,该元素解释了您所看到的行为。
相反,您需要遍历所有元素并单独应用speed
:
$(window).scroll(function(){
var scrolltop = $(window).scrollTop();
$(".parallax").each(function() {
var $el = $(this),
speed = $el.data("speed");
$el.css("backgroundPosition", "50% " + -(scrolltop * speed) + "px");
});
});
尝试...
jQuery(function( $ ){
// Enable parallax and fade effects on homepage sections
$(window).scroll(function(speed){
scrolltop = $(window).scrollTop()
scrollwindow = scrolltop + $(window).height();
var parallax = $(".parallax");
$.each(parallax, function(index, value) {
speed = $(parallax[index]).data("speed");
$(parallax[index]).css("backgroundPosition", "50% " + -(scrolltop*speed) + "px");
});
});
循环应允许将速度单独应用于每个视差类。