简体   繁体   English

在特定区域获取 DOM 元素的最佳(最快)方法是什么

[英]What's best (fastest) way to get DOM elements in specific area

I want to get all DOM elements within a selector area (created when press and drag left mouse, like photoshop, illustrator, figma selector).我想获取选择器区域内的所有 DOM 元素(在按住并拖动鼠标左键时创建,如 photoshop、illustrator、figma 选择器)。 as the following img:如下图所示: 在此处输入图片说明

在此处输入图片说明

All elements are absolute position with left, top, width, height attributes.所有元素都是具有left, top, width, height属性的绝对位置。 And the selector given a rectangle with left, top, bottom, right, width, height .选择器给出了一个矩形, left, top, bottom, right, width, height And please note that we have alot of elements (eg: 10,000 DOM elements), so if we loop through all 10,000 elements to check if it with in selector area, that's not good idea.请注意,我们有很多元素(例如:10,000 个 DOM 元素),所以如果我们遍历所有 10,000 个元素以检查它是否在选择器区域中,这不是一个好主意。

I've tried 2 solutions:我尝试了两种解决方案:

  1. Using intersection-observer to observer visible elements on screen first, then we only need to check in these elements.首先使用intersection-observer观察屏幕上可见的元素,然后我们只需要检查这些元素。
  2. Cache all elements with 4 objects:使用 4 个对象缓存所有元素:
    • byTops: store all elements with order top ascending byTops:以top升序存储所有元素
    • byBottoms: store all elements with order bottom ascending byBottoms:按bottom升序存储所有元素
    • byLefts: store all elements with order left ascending byLefts:以left升序存储所有元素
    • byRights: store all elements with order top ascending byRights: 存储所有元素以top顺序

And when we check, it maybe faster当我们检查时,它可能会更快

And this is DEMO for solution 1: Demo for solution 1这是解决方案 1 的演示:解决方案 1 的演示

Does anyone have a better solution for this scene?有没有人对这个场景有更好的解决方案? Please help me!请帮我!

thanks you very much!非常感谢你!

If you know the minimum size of each element they can select, you could potentially use document.elementFromPoint to get the elements selected.如果您知道他们可以选择的每个元素的最小尺寸,您可以潜在地使用document.elementFromPoint来获取选择的元素。

What I mean is, say they drew a selection, and each thing they can select is at least 40px x 60px.我的意思是,假设他们画了一个选区,他们可以选择的每个东西至少是 40px x 60px。 You could then do something like:然后,您可以执行以下操作:

let {top, left, right, bottom} = rectangleCoords;
const selectedElements = new Set();
for (let x = left; x <= right; x += 40) {
    for (let y = top; y <= bottom; y+= 60) {
        const el = document.elementFromPoint(x, y).closest('.thing-you-want');
        if (el) {
            selectedElements.add(el);
        }
    }
}

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

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