Arr*_*tch 5 jquery scroll window parallax
我正在尝试创建视差滚动效果。
该视差容器实现像这样:
< div class="parallax slide-1" >
< /div >
当它的容器滚动到 view时,我需要视差效果开始。
到目前为止,jQuery 工作正常。
但是:由于我可以在一页上有多个视差容器(例如一个在顶部 + 一个在底部),我需要它们由 jQuery独立处理。
目前效果是...
所以还不是完全的解决方案。
我认为它应该与 jQuerys .each() 一起工作,但到目前为止我无法真正让它工作。
我想当我尝试实现它时,我对某处的嵌套函数感到困惑。
这是我当前的代码:
$(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
}
}
});
})
Run Code Online (Sandbox Code Playgroud)
假设您想要执行的滚动是相同的(使用相同的视差方法等),您可以在类上使用 .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
}
});
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1695 次 |
| 最近记录: |