简体   繁体   中英

ScrollTop equal a value not working

I'm trying to run a script when scroll position is a certain value.

Why is this not working?

<script type="text/javascript">
    $(document).scroll(function () {

        if ($(document).scrollTop() == 1500) { 
        $.scrollLock(true);}
    });
</script>

When i change == to >= it does work, but that is not what I want. I want it only to work at 1500.

When you scroll in a browser the scrollbar doesn't go down in 1px segments, it jumps around. In Chrome, scrolling by one segment takes you up or down by 100px (see this demo ).

What you can do is be a bit flexible with your value. Rather then wanting it to fire at exactly 1500px, you can set it to fire between 1450 and 1550. This should capture the scroll in most browsers:

var scrollTop = $(document).scrollTop();
if (scrollTop >= 1450 && scrollTop <= 1550) { 
    $.scrollLock(true);
}

You can then take this a step further by forcing it to 1500 if it falls within that range:

if (scrollTop >= 1450 && scrollTop <= 1550) { 
    $(document).scrollTop(1500);
    $.scrollLock(true);
}

JSFiddle demo .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM