gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 08:09:47 25 4
gpt4 key购买 nike

我正在寻找一种非常快速的解决方案来解决 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com