Javascript 如何使用jQuery检测用户何时滚动到页面上的某个区域?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7182342/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 01:13:01  来源:igfitidea点击:

How to detect when the user has scrolled to a certain area on the page using jQuery?

javascriptjquery

提问by Mike

Possible Duplicate:
How to detect page scroll to a certain point in jQuery?
Check if element is visible after scrolling

可能的重复:
如何检测页面滚动到 jQuery 中的某个点?
滚动后检查元素是否可见

How can I detect when the user has reached this div:

如何检测用户何时到达此 div:

<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />

<div id="theTarget">I have been reached</div>

EDIT

编辑

Got the answer from this question:

从这个问题得到了答案:

Check if element is visible after scrolling

滚动后检查元素是否可见

So I just did this:

所以我只是这样做了:

function isScrolledIntoView(elem)
{
    var docViewTop = $(window).scrollTop();
    var docViewBottom = docViewTop + $(window).height();
    var elemTop = $(elem).offset().top;
    var elemBottom = elemTop + $(elem).height();
    return ((elemBottom >= docViewTop) && (elemTop <= docViewBottom) && (elemBottom <= docViewBottom) && (elemTop >= docViewTop));
}

$(window).scroll(function() {    
    if(isScrolledIntoView($('#theTarget')))
    {
        alert('visible');
    }    
});

回答by Simon Arnold

$(document).on('scroll', function() {
    if($(this).scrollTop()>=$('#theTarget').position().top){
        yourActionHere();
    }
})

Compare the scroll and your element position. Than call your function. No plugin required.

比较滚动和元素位置。比调用你的函数。不需要插件。

回答by Maxx

I think you can accomplish your goal by comparing values from your div position

我认为您可以通过比较 div 位置的值来实现您的目标

var divPosition = $("#theTarget").offset().top;

and the window scroll position

和窗口滚动位置

var scrollPosition = window.scrollY;

回答by Wayne

There is a jquery appear plugin that I believe does exactly what you are asking.

有一个 jquery 出现插件,我相信它完全符合您的要求。

http://plugins.jquery.com/project/appear

http://plugins.jquery.com/project/appear

$('#theTarget').appear(function() {
  $(this).text('Hello world');
});

It also ties into resize, and initial window size ... etc, etc, etc.

它还与调整大小和初始窗口大小有关……等等等等。