[英]jQuery trigger action when a user scrolls past a certain part of the page
Hey all, I need a jQuery action to fire when a user scrolls past certain locations on the page.大家好,当用户滚动经过页面上的某些位置时,我需要一个 jQuery 动作来触发。 Is this even possible with jQuery?这甚至可以用 jQuery 实现吗? I have looked at .scroll in the jQuery API and I don't think this is what I need.我在 jQuery API 中查看了 .scroll,但我认为这不是我需要的。 It fires every time the user scrolls, but I need it to fire just when a user passes a certain area.每次用户滚动时它都会触发,但我需要它在用户经过某个区域时触发。
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
}
});
http://jsfiddle.net/babumxx/hpXL4/ http://jsfiddle.net/babumxx/hpXL4/
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/
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
}
});
})
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.