【问题标题】:Track when user scrolls past div that is in an array跟踪用户滚动经过数组中的 div 的时间
【发布时间】:2015-10-13 03:48:37
【问题描述】:

有没有办法设置一个html元素数组。比如Section_1、Section_2 和Section_3 在所述数组中。当用户向下滚动页面时,并且仅在向下滚动时,是否可以检查用户是否滚动了该数组中指定的部分?有点像……

var readerLocation = 150;
var content = ['block_1', 'block_2', 'block_3'];

bottom = $(window).height() + $(window).scrollTop();
height = $(document).height();

// If user starts to scroll send an event
if (bottom > readerLocation) {
  console.log('started reading');
  var i = 0;
  for (block in content) {
    console.log(content[i]);
    //check if scrolled past element in array here()
    i++;
  }
}

【问题讨论】:

  • 你的 readerLocation 的目的是什么?

标签: javascript jquery html arrays scroll


【解决方案1】:

您可以设置一个$(window).scroll() 事件。

对于数组中的每个元素,您希望找到其在页面中的偏移量,并将其与您当前的$(window).scrollTop() 进行比较。每当它通过时说Section_1 的offset().top,那么您就知道它在第1 节中,尚未到达第2 节。

【讨论】:

  • 我觉得我说的不对,你觉得这怎么样? jsfiddle.net/rs9dftu5/5 另外,请忽略占位符文本...这是 Slipsum。
  • offset 是一个函数,所以你需要offset().top
【解决方案2】:

这是一个代码示例,可让您接近您想要的位置:

需要注意的几点:

  1. 通过在数组 foreach 循环中指定条件来运行代码。
  2. 确保跟踪变量而不是动态应用代码。
  3. 由于您使用的是 jQuery,因此请充分利用 $(window).scroll 来跟踪您的滚动事件。

$(document).ready(function(){
	var lastScrollTop = 0,
        block = ['block_2', 'block_5', 'block_7'];

	$(window).scroll(function(event){
    	var st = $(this).scrollTop(),
            block_2_offset = $('#' + block[0]).offset().top;
       	
        if (st > lastScrollTop){
            // downscroll
            block.forEach(function(block, i) {
                // check if we passed through on scroll down, then do something, modify the condition for a more specialized response
                if(st >= $('#' + content[i]).offset().top){
                    // do something
                }
            });
        }
        lastScrollTop = st;
   	});
});
div {
    padding-bottom: 500px;
    text-align: center;
}
div:nth-child(3) {
    background-color: blue;
}
div:nth-child(6) {
    background-color: yellow;
}
div:nth-child(8) {
    background-color: pink;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="block_1">
    block 1
</div>
<div id="block_2">
    block 2
</div>
<div id="block_3">
    block 3
</div>
<div id="block_4">
    block 4
</div>
<div id="block_5">
    block 5
</div>
<div id="block_6">
    block 6
</div>
<div id="block_7">
    block 7
</div>
<div id="block_8">
    block 8
</div>
<div id="block_9">
    block 9
</div>

【讨论】:

    猜你喜欢
    • 2014-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多