当用户滚动浏览页面的某个部分时,jQuery触发操作

时间:2011-01-07 15:36:14

标签: javascript jquery

嘿所有,当用户滚动浏览页面上的某些位置时,我需要触发jQuery操作。这甚至可以用jQuery吗?我在jQuery API中查看了.scroll,我认为这不是我需要的。每次用户滚动时都会触发,但我需要在用户经过某个区域时触发它。

3 个答案:

答案 0 :(得分:45)

使用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/

答案 1 :(得分:20)

jQuery中的Waypoints应该这样做: http://imakewebthings.github.com/jquery-waypoints/

$('#my-el').waypoint(function(direction) {
  console.log('Reached ' + this.element.id + ' from ' + direction + ' direction.');
});

jQuery waypoints插件文档:http://imakewebthings.com/waypoints/guides/jquery-zepto/

答案 2 :(得分:9)

要在一个页面上只触发一次任何操作,我修改了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

            }
    });

})


向下滚动到“运行代码段”

您可以在此检查工作代码段的示例;

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>