简体   繁体   English

获取视口Javascript中的所有元素

[英]Get all elements in viewport Javascript

I wonder if it is possible (in javascript or jquery but without any plugins) to get all elements (for example table rows tr) in current viewport without looping through each of them?我想知道是否有可能(在 javascript 或 jquery 但没有任何插件的情况下)在当前视口中获取所有元素(例如表行 tr)而不遍历每个元素? I found a lot of examples how to check if specified element is in current viewport, but what I need is a function returns a list of all elements in current viewport.我找到了很多如何检查指定元素是否在当前视口中的示例,但我需要的是一个函数返回当前视口中所有元素的列表。 I need this for virtualization because this table should have an infinite capacity and looping through each row from two millions rows is quite inefficient :)我需要这个来进行虚拟化,因为这个表应该有无限的容量,从两百万行循环遍历每一行效率很低:)

Is there any reasonable way to do this?有什么合理的方法可以做到这一点吗?

Assuming you're not doing anything fancy with positioning, table rows in the viewport can be found with a binary search.假设您没有对定位进行任何花哨的操作,则可以通过二分搜索找到视口中的表行。 For example, for 200000 rows, about 18 lookups are required to locate the first row on the page ( jsfiddle , warning: slow to load).例如,对于 200000 行,大约需要 18 次查找才能定位页面上的第一行( jsfiddle ,警告:加载缓慢)。 This can be extended to find the last element as well, or you could just loop through the elements starting from the first until you find one that is no longer visible.这也可以扩展为查找最后一个元素,或者您可以从第一个元素开始循环遍历元素,直到找到不再可见的元素。

var rows = table.children().children();
var start = 0;
var end = rows.length;
var count = 0;

while(start != end) {
    var mid = start + Math.floor((end - start) / 2);
    if($(rows[mid]).offset().top < document.documentElement.scrollTop)
        start = mid + 1;
    else
        end = mid;
}

Obviously this does not work well if anything is floated, absolutely positioned, etc. In short: The nodes being searched must be in order such that rows[N-1].top <= rows[N].top .显然,如果有任何东西是浮动的、绝对定位的等等,这不会很好地工作。简而言之:被搜索的节点必须按顺序排列,使得rows[N-1].top <= rows[N].top For something such as a table, this should be true if no styling is applied and no multi-row cells exist.对于诸如表格之类的内容,如果未应用样式且不存在多行单元格,则应为真。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM