[英].scroll() is only running once
I'm trying to create a small snippet for a sticky sidebar with jQuery. 我正在尝试使用jQuery为粘性侧边栏创建一个小片段。 For some reason, the function inside of
.scroll()
is only running once instead of running at every scroll event. 由于某种原因,
.scroll()
内部的函数仅运行一次,而不是在每次滚动事件时都运行。 What could I be doing wrong? 我可能做错了什么?
var sticky = $('#sticky');
var staticSticky = $(sticky).offset().top;
$(window).scroll(moveEl(sticky, staticSticky));
function moveEl(element, staticElToTop){
if( $(window).scrollTop() >= staticElToTop ){
$(element).css('top', $(window).scrollTop() + 'px');
}
}
See here for the entire attempt: http://codepen.io/ExcellentSP/pen/GqZwVG 整个尝试请参见此处: http : //codepen.io/ExcellentSP/pen/GqZwVG
The code above is not fully functional. 上面的代码未完全正常运行。 I'm just trying to get the scroll event to work properly before I continue.
在继续之前,我只是想让滚动事件正常工作。
You need to wrap content of your your moveEl
method into the function (to be returned for $(window).scroll()
) like this: 您需要将
moveEl
方法的内容包装到函数中(将为$(window).scroll()
),如下所示:
var sticky = $('#sticky');
var staticSticky = $(sticky).offset().top;
$(window).scroll(moveEl(sticky, staticSticky));
function moveEl(element, staticElToTop) {
return function() {
if( $(window).scrollTop() >= staticElToTop ){
$(element).css('top', $(window).scrollTop() + 'px');
}
}
}
Explanation: The key difference is that you call a function and it returns undefined
by default, so it equals to $(window).scroll(undefined)
. 说明:关键区别在于您调用一个函数,并且该函数默认情况下返回
undefined
,因此它等于$(window).scroll(undefined)
。 Since you actually called it, you see it's fired only once which is obvious. 由于您实际上已调用它,因此您仅看到它被触发了一次,这很明显。
As soon as you return a function within moveEl
method, .scroll()
gets a handler, so it becomes $(window).scroll(handler)
. 只要在
moveEl
方法中返回一个函数, .scroll()
就会获得一个处理程序,因此它将变成$(window).scroll(handler)
。 So it will work now as expected. 因此它将现在按预期工作。
In doing that $(window).scroll(moveEl(sticky, staticSticky));, you ask to javascript to execute the function. 在执行该$(window).scroll(moveEl(sticky,staticSticky));时,您要求使用javascript执行该函数。 You don't pass its reference.
您没有通过其参考。
$(window).scroll(function(){
moveEl(sticky, staticSticky);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.