滚动时:如果scrollTop()等于或达到值execute事件 [英] While Scrolling: if scrollTop() equals to or reaches a value execute event

查看:76
本文介绍了滚动时:如果scrollTop()等于或达到值execute事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在向下滚动到某个点/值时触发事件,然后在向上和向下滚动时再次执行。

I'm trying to fire an event when scrolling down to a certain point/value and execute again when scroll back up and down again.

我试过:

$(window).scroll(function(){
    var sTop = $(this).scrollTop();

    if(sTop == 300){
        //execute event - failed
    }

});

上述内容不会通过鼠标滚轮和拖动滚动条触发任何内容。但当我将条件更改为大于或等于时,事件正在执行,但在向下滚动时多次执行。

The above does not fire anything with the both mousewheel and dragging the scrollbar. but when I changed the condition to greater than or equal to, the event is being executed but multiple times when scrolling further down.

if(sTop >= 300){
    //execute event - success
}

我也尝试更改条件值,有时候事件被触发。

I also tried changing the condition value and some times the event is being fired.

if(sTop == 333 /* or 431, 658, etc. */){
    //execute event - sometimes success
}

这是我的测试小提琴

如果滚动速度快,那么 scroll()函数有时会跳过一个值吗?

Could it be that scroll() function sometimes skips a value if you scroll fast?

有人可以解释这个问题并帮助我解决如何在 $(窗口).scrollTop()==时触发事件的方法'值'。谢谢

Can someone explain the issue and help me with a workaround on how to trigger an event when the $(window).scrollTop() == 'value'. Thanks

推荐答案

您正面临这个问题,因为无法保证滚动将以1为增量完成。例如,一些滚轮的值增加30.这意味着您将在30,60,90等处获得滚动事件。

You're facing this issue because there are no guarantees that scrolling will be done in increments of 1. For example, some scroll wheels increment in values of 30. This means that you'd get a scroll event on 30, 60, 90, etc.

测试是否滚动的最佳方法已达到你的极限是看它是否已超过你想要的点,然后将滚动重置为你想要的精确点。所以你要这样做:

The best way to test if scrolling has reached your limit is to see if it has gone past the point you're wanting, then resetting the scroll to the precise point you're wanting. So you'd do:

if(sTop >= 300){
    $(window).scrollTop(300);
}

这是一个带有工作示例的JSFiddle的更新链接: http://jsfiddle.net/bC3Cu/4/

Here's an updated link to your JSFiddle with a working example: http://jsfiddle.net/bC3Cu/4/

如果你看一下可滚动区域的增量单位/ divs in javascript?它描述了如何将其设置为可以覆盖滚动增量的位置。使用该方法,您应该能够预测用户滚动的单位数量,而不会阻止他们向下滚动页面。

If you take a look at unit of increment in scrollable areas / divs in javascript? it describes how to set it to where you can override the scroll increment. Using that method, you should be able to predict how many units the user has scrolled without preventing them from scrolling further down the page.

这篇关于滚动时:如果scrollTop()等于或达到值execute事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆