我正在开发一个视差网站,我想在滚动停止时缓和元素。所以我开发了一个插件来检测滚动何时停止,一旦停止,然后平滑元素的移动(对象向用户滚动的方向移动 5 个像素)。它有效,但仅适用于插件应用到的最后一个元素。当我尝试调试时,我看到两个元素在内部仍然有效,$(window).scroll(function(event) {
但是一旦我们到达$(window).scrollStopped(function(){
,只有最后一个元素有效。有什么解决办法吗?
// Scroll Direction set
var lastScrollTop = 0, scrollDirection = "";
$(window).scroll(function(event){
var st = $(this).scrollTop();
if (st > lastScrollTop){
scrollDirection = "down";
} else {
scrollDirection = "up";
}
lastScrollTop = st;
});
// Scroll Stopped detection
$.fn.scrollStopped = function(callback) {
$(this).scroll(function(){
var self = this, $this = $(self);
if ($this.data('scrollTimeout')) {
clearTimeout($this.data('scrollTimeout'));
}
$this.data('scrollTimeout', setTimeout(callback,250,self));
});
};
// Smooth ending
$.fn.smoothStop = function () {
var $this = $(this);
$(window).scroll(function(event) {
$(window).scrollStopped(function(){
var top = parseFloat($this.css("top"));
if(scrollDirection == "down")
{
console.log(top, $this);
var new_top = top + 5;
$this.animate({
top: new_top + 'px'},
1000);
}
else{
var new_top = top - 5;
$this.animate({
top: new_top + 'px'},
1000);
}
});
});
};
$(".g6").smoothStop();
$(".g2").smoothStop();