Javascript jQuery函数将丢失被调用的元素并只保留最后一个调用方
我正在开发一个视差站点,我想在滚动停止时释放元素。所以我开发了一个插件来检测滚动何时停止,一旦停止,然后平滑元素的移动(对象向用户滚动的方向移动5个像素)。它可以工作,但只适用于插件应用到的最后一个元素。当我尝试调试时,我看到两个元素仍然在Javascript jQuery函数将丢失被调用的元素并只保留最后一个调用方,javascript,jquery,Javascript,Jquery,我正在开发一个视差站点,我想在滚动停止时释放元素。所以我开发了一个插件来检测滚动何时停止,一旦停止,然后平滑元素的移动(对象向用户滚动的方向移动5个像素)。它可以工作,但只适用于插件应用到的最后一个元素。当我尝试调试时,我看到两个元素仍然在$(窗口)中有效。滚动(函数(事件){,但一旦我们到达$(窗口)。滚动停止(函数(){),只有最后一个元素有效。有解决方案吗 // Scroll Direction set var lastScrollTop = 0, scrollDirection = ""
$(窗口)中有效。滚动(函数(事件){
,但一旦我们到达$(窗口)。滚动停止(函数(){
),只有最后一个元素有效。有解决方案吗
// 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();
//滚动停止检测
$.fn.scrollStopped=函数(回调){
$(this).scroll(function(){您能准备一个JSFIDLE吗?当然,请给我几分钟时间,然后我将移动更改为15px,这样就可以看到移动了
// Scroll Stopped detection
$.fn.scrollStopped = function(callback) {
$(this).scroll(function(){ <-- this is the window
var self = this, $this = $(self);
if ($this.data('scrollTimeout')) {
clearTimeout($this.data('scrollTimeout')); <----timeout is removed from window
}
$this.data('scrollTimeout', setTimeout(callback,250,self)); <----timeout is set to window
});
};