当用户滚动到特定 div 时运行 javascript 函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20851518/
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-10-27 19:27:08  来源:igfitidea点击:

Run javascript function when user scrolls to a specific div

javascriptjquerycsshtml

提问by kduan

I have a different function I want to run each time a user scrolls to another div or to another section of the page. Is there anyway I can do that?

每次用户滚动到另一个 div 或页面的另一个部分时,我想运行一个不同的函数。反正我能做到吗?

回答by Vikas Ghodke

Allready Answered here -->> Dynamic Scroll Position in Jquery

已在此处回答-->> Jquery 中的动态滚动位置

There is a great plugin to do this called WAYPOINT

有一个很棒的插件可以做到这一点,叫做WAYPOINT

I have setup an example on jsfiddle check it out

我已经在jsfiddle上设置了一个示例,请查看

HTML

HTML

<div class="first"></div>
<div class="second"></div>

CSS

CSS

.first {
    background:green;
    height: 600px;
    width:100%;
}
.second {
    background:red;
    height: 600px;
    width:100%;
}

JS

JS

$('.second').waypoint(function() {
    alert('You have scrolled to an entry.');
}, {
    offset: '100%'
});

回答by emerkulova

There're many ways to do this. The most simplest method:

有很多方法可以做到这一点。最简单的方法:

var element = $('#my-div');

function myFunction() {
    alert('I am here!');
}

$(window).scroll(function(){
    var docViewTop = $(window).scrollTop();
    var docViewBottom = docViewTop + $(window).height();

    var elemTop = $(elem).offset().top;
    var elemBottom = elemTop + $(elem).height();

    if ((elemBottom <= docViewBottom) && (elemTop >= docViewTop)) {
        myFunction();
    }
});

Also there're jQuery Appear pluginand Waypoints plugin:

还有jQuery Appear 插件Waypoints 插件

$('#my-div').appear(function() {
    alert('I am here!');
});

$('#my-div').waypoint(function() {
    alert('I am here!');
});