Goal:
我正在尝试创建一个视差滚动 effect.
The 视差容器是这样实现的:
< div class="parallax slide-1" >
< /div >
我需要启动视差效果,当它的容器已滚动到视图中.
- 一旦有了离开视图,效果需要停止。
问题:
到目前为止,jQuery 运行良好。
但是:既然我可以拥有一页上有多个视差容器(例如,顶部一个 + 底部一个)我需要对它们进行治疗独立地通过 jQuery。
目前的效果是...
- 1.) 一旦第一个视差容器滚动到视图中,就会触发每个视差容器
- 2.) 一旦每个视差容器离开视图,它就会停止。
所以还不是完全的解决方案。
Thoughts
我认为它应该与 jQuerys .each() 一起使用,但到目前为止我还无法真正让它工作。
我认为当我尝试实现它时,我对某个地方的嵌套函数感到困惑。
Code
这是我当前的代码:
$(document).ready(function(){
$.fn.is_on_screen = function(){
var win = $(window);
var viewport = {
top : win.scrollTop(),
left : win.scrollLeft()
};
viewport.right = viewport.left + win.width();
viewport.bottom = viewport.top + win.height();
var bounds = this.offset();
bounds.right = bounds.left + this.outerWidth();
bounds.bottom = bounds.top + this.outerHeight();
return (!(viewport.right < bounds.left || viewport.left > bounds.right || viewport.bottom < bounds.top || viewport.top > bounds.bottom));
};
$(window).scroll(function(){ // Bind window scroll event
if( $('.parallax').length > 0 ) { // Check if target element exists in DOM
if( $('.parallax').is_on_screen() ) { // Check if target element is visible on screen after DOM loaded
// ANIMATE PARALLAX EFFECT
// If Parallax Element is scrolled into view do...
// Variables
var speed = 2.5;
var calc = (-window.pageXOffset / speed) + "px " + (-window.pageYOffset / speed) + "px";
var container = $(".parallax");
// Function
container.css({backgroundPosition: calc});
} else {
// ...otherwise do nothing
}
}
});
})
假设您想要执行的滚动是相同的(使用相同的视差方法等),您可以在类上使用 .each 。例子:
$(window).scroll(function(){ // Bind window scroll event
$( ".parallax" ).each(function() {
if( $( this ).is_on_screen() ) { // Check if target element is visible on screen after DOM loaded
// ANIMATE PARALLAX EFFECT
// If Parallax Element is scrolled into view do...
// remember to replace ('.paralax') with (this)
// Variables
var speed = 2.5;
var calc = (-window.pageXOffset / speed) + "px " + (-window.pageYOffset / speed) + "px";
var container = $( this );
// Function
container.css({backgroundPosition: calc});
} else {
// ...otherwise do nothing
}
});
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)