javascript - 如何使用 JavaScript/jQuery 跟踪 div 滚动到页面上的点

标签 javascript jquery html scroll

我正在寻找一种非常快速的解决方案来解决 div 滚动问题。

我有一组 div,例如论坛帖子,它们一个放在另一个之上。当页面向下或向上滚动时,我想知道其中一个 div 何时击中页面上的任意点。

我尝试的一种方法是向每个项目添加 onScroll 事件,但随着项目数量的增加,页面确实开始滞后。

有人知道更有效的方法吗?谢谢/w

最佳答案

好吧,我对这一切都很陌生,所以也许有人应该纠正我:)

我建议

  • 缓存帖子位置
  • 缓存当前
  • 使用二分搜索

演示:http://jsfiddle.net/zYe8M/

<div class="post"></div>
<div class="post"></div>
<div class="post"></div>

...

var posts = $(".post"), // our elements
    postsPos = [], // caсhe for positions
    postsCur = -1, // cache for current
    targetOffset = 50; // position from top of window where you want to make post current

// filling postsPos with positions
posts.each(function(){
    postsPos.push($(this).offset().top);
});

// on window scroll
$(window).bind("scroll", function(){
  // get target post number
  var targ = postsPos.binarySearch($(window).scrollTop() + targetOffset);
  // only if we scrolled to another post
  if (targ != postsCur) {
    // set new cur
    postsCur = targ;
    // moving cur class
    posts.removeClass("cur").eq(targ).addClass("cur");
  }
});

// binary search with little tuning on return to get nearest from bottom
Array.prototype.binarySearch = function(find) {
  var low = 0, high = this.length - 1,
      i, comparison;
  while (low <= high) {
    i = Math.floor((low + high) / 2);
    if (this[i] < find) { low = i + 1; continue; };
    if (this[i] > find) { high = i - 1; continue; };
    return i;
  }
  return this[i] > find ? i-1 : i;
};

关于javascript - 如何使用 JavaScript/jQuery 跟踪 div 滚动到页面上的点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14349918/

相关文章:

html - 开发时如何在我的页面上查看 Bootstrap 网格大小?

javascript - 如何使用 JavaScript 更改复选框背景

javascript - Javascript 可以访问 native 图像大小吗?

javascript - 使用 Javascript/jQuery 从 iframe 选择 HTML

javascript - 如何在 JavaScript 中更改跨度内多个位置的文本(不使用 getElementbyId)?

css - HTML 布局,菜单文字间距错误,无法居中对齐

javascript - 使用正则表达式和 javascript 将 HTTP url 重写为 HTTPS

javascript - 在 bash 脚本中使用进程替换时, Node 找不到模块

javascript - 如何使用 JavaScript 从图像中提取文本

JavaScript 按字符数过滤 &lt;input&gt; 值的数组