$(window).scrollTop 与 $(window).scroll() 事件关联,行为奇怪
当窗口滚动超过一定数量的像素时,我试图触发一个函数。
这是我的代码:
$(window).scroll(function(){
if( $(this).scrollTop() >= 100 ) {
someFunction();
} else {
someOtherFunction();
}
});
它有点工作,但是滚动后在触发函数之前会有大约 2-4 秒的延迟,或者根本不会触发函数。
在 Safari / Chrome 中尝试过。不知道有没有帮助!
I'm trying to trigger a function when the window is scrolled more than a certain number of pixels.
Here's my code:
$(window).scroll(function(){
if( $(this).scrollTop() >= 100 ) {
someFunction();
} else {
someOtherFunction();
}
});
It kinda works, but there's either a delay of around 2-4 seconds after scrolling before the function(s) are fired or else the functions aren't triggered at all.
Tried it out in Safari / Chrome. Don't know if that helps or not!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
它可以在 OSX 上的 Chrome15/Safari5.1/FF7 中使用 jQuery 1.6.1 + 鼠标滚轮/滚动条。你在这两个函数中做什么?为了进行测试,我在
someFunction
中放置了一个简单的alert(),而在someOtherFunction
中没有放置任何内容。请记住,每次滚动事件触发时都会执行其中一个函数,除非您在调用它后停止它...例如,在滚动到 100px 线以下后,会多次调用 someFunction。
John Resig:将处理程序附加到窗口滚动事件是一个非常非常糟糕的主意。
It works using jQuery 1.6.1 + mousewheel / scrollbar in Chrome15/Safari5.1/FF7 on OSX. What are you doing in those two functions? For testing, I put a simple alert() in
someFunction
and nothing insomeOtherFunction
.Remember that one of those functions is executed every time the scroll-event fires unless you stop it once it was called... e.g. someFunction is called a lot after you scrolled below the 100px line.
John Resig: It's a very, very, bad idea to attach handlers to the window scroll event.
如果您通过按住单击按钮而不是使用滚轮来滚动,我相信在您释放单击按钮之前该事件不会触发。
您是否考虑过运行一个循环来检查
scrollTop
?编辑:
我只是使用窗口滚动事件检查了我的一个旧项目,它在相同的事件下运行完美。
我假设你的脚本包含在里面:
If you're scolling by holding in the click-button instead of using the scroll wheel, I believe the event won't fire until you release the click-button.
Have you considered running a loop that checks the
scrollTop
instead?EDIT:
I just check an old project of mine using window scroll event, and it runs perfect with the same event.
I asume you have this script of yours wrapped inside:
该代码看起来不错并且适合我。
正如 Wolfram 所说,将处理程序直接附加到滚动事件并不是一个好主意,因为这会触发大量事件并可能使用户的系统变得缓慢。
我建议使用 Ben Alman 的 jquerythrottle/debounce 插件。
The code looks fine and works for me.
As Wolfram says, it's rarely a good idea to attach handlers directly to the scroll event, as this fires a lot and can bring the user's system to a crawl.
I'd recommend using Ben Alman's jquery throttle/debounce plugin.