【问题标题】:how to get first visible row from the table when it is scrolled滚动时如何从表中获取第一个可见行
【发布时间】:2014-04-08 12:01:12
【问题描述】:
假设我在表中有 10 行。其中只有 5 行在屏幕上可见,这意味着当表加载时,1、2、3、4、5 行是可见的。当我向下滚动 1 行时,第 2 行、3、4、5、6 是可见的。 Javascript 或 jquery 有什么方法可以找到屏幕上的第一行吗?我尝试过可能的方法:
if(tr.position().top > $(table).position().top)
{
}
else
{
}
在这里,我将每行的位置与桌面位置进行比较。但不幸的是,每次我得到相同的位置,即使我滚动。如何做到这一点?
【问题讨论】:
标签:
javascript
jquery
html
【解决方案1】:
使用来自here 的代码并进行一些修改:
JS 代码(使用div 代替tr):
$(function () {
$(window).scroll(function () {
var first = null; // element at the top
$("div").each(function(){ // check each div
// if it is visivle, and is there is not first element yet,
if( isScrolledIntoView($(this)) && !first) {
first = $(this); // this is the first
first.addClass("seen"); // visual aspect
}
// unnecessary, only for visual
else
$(this).removeClass("seen"); // remove class seen (visual)
});
});
// foreign code
function isScrolledIntoView(elem) {
// .....
}
});
DEMO
滚动查看效果
【解决方案2】:
您可以在滚动事件回调上执行类似的操作(使用 JQuery),使用超时来限制事件的频率,加上最后找到的可见元素的光标,以便在下一个执行更快的搜索事件。这里的“this”是您的观点的上下文:
onScroll: function(e) {
if (this.scrollEvent) {
return;
}
this.scrollEvent = true;
setTimeout(function(view) {
// @replace you should check here is you view still exists using a status on your view context
if (view.isDestroyed) {
return;
}
view.scrollEvent = false;
var top = $('youselector on tbody').parent().parent().offset().top;
if (view.previousTopElement) {
if (view.previousTopElement.offset().top <= top) {
// the element is the previous, or on bottom of previous
var element = view.previousTopElement;
var i = view.previousTopElementIndex;
view.previousTopElement = null;
while (element.length) {
if (element.offset().top + element.height() >= top) {
// you can uses i + 1 for a 1 based position to display
view.previousTopElement = element;
view.previousTopElementIndex = i;
return;
}
element = element.next();
++i;
}
} else if (view.previousTopElement.offset().top > top) {
// the element is before the previous
var element = view.previousTopElement;
var i = view.previousTopElementIndex;
this.previousTopElement = null;
while (element.length) {
if (element.offset().top <= top) {
// you can uses i + 1 for a 1 based position to display
view.previousTopElement = element;
view.previousTopElementIndex = i;
return;
}
element = element.prev();
--i;
}
}
}
// no previous, get all rows
var rows = $('youselector on tbody').children('tr');
view.previousTopElement = null;
view.previousTopElementIndex = 0;
$.each(rows, function (i, el) {
var element = $(el);
if (element.offset().top + element.height() >= top) {
// you can uses i + 1 for a 1 based position to display
view.previousTopElement = element;
view.previousTopElementIndex = i;
return false;
}
});
}, 100, this); // you can adjust the timeout, pass your view context
}
这就是想法。就我而言,我会进行此优化,因为我可以有很多行。