给定网页上的两个点和一组 DOM 元素,如何找出位于这两个点定义的矩形区域内的 DOM 元素的子集?
我正在开发一个基于网络的画廊,其中每张照片都包含在li
标签。当用户用鼠标拖出一个矩形区域时,所有li
矩形内的元素被标记为已选择。
更喜欢 jQuery 解决方案,因为它是一种简洁且高效的方法。
尝试这样的事情:
// x1, y1 would be mouse coordinates onmousedown
// x2, y2 would be mouse coordinates onmouseup
// all coordinates are considered relative to the document
function rectangleSelect(selector, x1, y1, x2, y2) {
var elements = [];
jQuery(selector).each(function() {
var $this = jQuery(this);
var offset = $this.offset();
var x = offset.left;
var y = offset.top;
var w = $this.width();
var h = $this.height();
if (x >= x1
&& y >= y1
&& x + w <= x2
&& y + h <= y2) {
// this element fits inside the selection rectangle
elements.push($this.get(0));
}
});
return elements;
}
// Simple test
// Mark all li elements red if they are children of ul#list
// and if they fall inside the rectangle with coordinates:
// x1=0, y1=0, x2=200, y2=200
var elements = rectangleSelect("ul#list li", 0, 0, 200, 200);
var itm = elements.length;
while(itm--) {
elements[itm].style.color = 'red';
console.log(elements[itm]);
}
对于普通的 JS 解决方案,请查看这支笔:https://codepen.io/ArtBIT/pen/KOdvjM https://codepen.io/ArtBIT/pen/KOdvjM
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)