Javascript 当用户滚动经过页面的某个部分时 jQuery 触发动作
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4627203/
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
jQuery trigger action when a user scrolls past a certain part of the page
提问by JJ Nold
Hey all, I need a jQuery action to fire when a user scrolls past certain locations on the page. Is this even possible with jQuery? I have looked at .scroll in the jQuery API and I don't think this is what I need. It fires every time the user scrolls, but I need it to fire just when a user passes a certain area.
大家好,当用户滚动经过页面上的某些位置时,我需要一个 jQuery 动作来触发。这甚至可以用 jQuery 实现吗?我在 jQuery API 中查看了 .scroll,但我认为这不是我需要的。每次用户滚动时它都会触发,但我需要它在用户经过某个区域时触发。
回答by jondavidjohn
Use the jquery event .scroll()
使用 jquery 事件 .scroll()
$(window).on('scroll', function() {
var y_scroll_pos = window.pageYOffset;
var scroll_pos_test = 150; // set to whatever you want it to be
if(y_scroll_pos > scroll_pos_test) {
//do stuff
}
});
回答by chris
Waypoints in jQuery should do it: http://imakewebthings.github.com/jquery-waypoints/
jQuery 中的航点应该这样做:http: //imakewebthings.github.com/jquery-waypoints/
$('#my-el').waypoint(function(direction) {
console.log('Reached ' + this.element.id + ' from ' + direction + ' direction.');
});
jQuery waypoints plugin documentation: http://imakewebthings.com/waypoints/guides/jquery-zepto/
jQuery 航点插件文档:http: //imakewebthings.com/waypoints/guides/jquery-zepto/
回答by Mohammad Mursaleen
To fire any action only once on a single page I have modified jondavid's snippet as following.
为了在单个页面上只触发一次任何操作,我修改了 jondavid 的代码片段如下。
jQuery(document).ready(function($){
$triggered_times = 0;
$(window).on('scroll', function() {
var y_scroll_pos = window.pageYOffset;
var scroll_pos_test = 150; // set to whatever you want it to be
if(y_scroll_pos > scroll_pos_test && $triggered_times == 0 ) {
//do your stuff over here
$triggered_times = 1; // to make sure the above action triggers only once
}
});
})
Scroll down to Run code snippet
向下滚动到运行代码片段
Here you can check example of working code snippet;
在这里您可以查看工作代码片段的示例;
jQuery(document).ready(function($){
$triggered_times = 0;
$(window).on('scroll', function() {
var y_scroll_pos = window.pageYOffset;
var scroll_pos_test = 150; // set to whatever you want it to be
if(y_scroll_pos > scroll_pos_test && $triggered_times == 0 ) {
alert('This alert is triggered after you have scroll down to 150px')
$triggered_times = 1; // to make sure the above action triggers only once
}
});
})
p {
height: 1000px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<p>scroll down this block to get an alert</p>
</body>