search

Home  >  Q&A  >  body text

javascript - Implement the mouse to draw a div frame and obtain the dom element covered by the div

Similar to this effect, move the mouse and pull a p box to select the dom element covered by p.
Do you have any good ideas that can be implemented


The method I came up with is to judge the offsetLeft, offsetTop of p and the offsetLeft, offsetTop of each element that needs to be selected. If the dom element is smaller than the offsetLeft Top of p, it is selected by the frame.
But the bad thing is that you need to traverse the offset attribute value of each element every time. Because there are many elements, there are hundreds. 1. Obtaining the attribute value will cause a lot of backflow, 2. It is too much to judge each time.


So I want to brainstorm and ask for help if anyone has a better way


I looked for the effect of a network disk before, and wanted to express it vividly, but that one was relatively simple, and the scene was really a little more complicated

仅有的幸福仅有的幸福2748 days ago566

reply all(4)I'll reply

  • PHP中文网

    PHP中文网2017-05-19 10:11:21

    It depends on how you think about it. I provide a simple method.
    When mousemove, get e.target and save it, and then filter out what you want through the function function. It’s that simple

    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-05-19 10:11:21

    Take Baidu Netdisk as an example. My idea is: because the height of each list item is fixed, you only need to compare the intersection of the rectangle formed when the mouse is dragged with the rectangle of the entire list element, and the amount of calculation will be much smaller. .

    The specific method is:

      When
    1. mousedown, calculate the starting list item index
      2.(offsetTop of 起始的列表项 + offsetTop of mouseup) / height of the list item, and then ceil the result to get the selected number.

    2. We have the index of the starting list item and the number of selected items, so it is easy to calculate which elements are selected.

    reply
    0
  • 给我你的怀抱

    给我你的怀抱2017-05-19 10:11:21

    The height of the parent container, the scrollTop/list item height of the parent container is fixed, the relative top of the rectangle, and the height of the rectangle
    These variables should be enough

    reply
    0
  • 大家讲道理

    大家讲道理2017-05-19 10:11:21

    按下标记关闭;
    按下点坐标 = {x: null; y: null};
    抬起点坐标 = {x: null; y: null};
    已选取元素数组 = [];
    document.onmousedown {
        按下标记开启
        按下点坐标 = {x: 鼠标当前横向偏移; y: 鼠标当前纵向偏移};
    }
    
    待选元素.onmouseover {
        如果按下标记开启,加入已选取元素数组
    }
    
    document.onmouseup {
        按下标记关闭
        清空已选取元素数组
        抬起点坐标 = {x: 鼠标当前横向偏移; y: 鼠标当前纵向偏移};
    }
    
    利用已选取元素数组操作已选中的元素
    利用按下点坐标、抬起点坐标绘制框选层

    The above is the complete logic, please try to write the code yourself!

    reply
    0
  • Cancelreply