本文介绍了在页面的矩形区域内获取DOM元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在网页和一组DOM元素上给出两点,如何找出位于由两点定义的矩形区域内的DOM元素的子集?
Given two points on a webpage and a set of DOM elements, how to find out the subset of those DOM elements that sit inside the rectangle area defined by the two points?
我正在开发一个基于网络的图库,其中每张照片都包含在 li
标记中。当用户使用鼠标拖出矩形区域时,矩形内的所有 li
元素都会标记为已选中。
I am working on a web-based gallery, in which every photo is wrapped in a li
tag. When a user drag out a rectangle area with mouse, all li
elements inside the rectangle are marked as selected.
喜欢jQuery解决方案,以减少冗长和有效的方式。
Prefer a jQuery solution for less wordy and an efficient way.
推荐答案
尝试这样的事情:
// 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]);
}
这篇关于在页面的矩形区域内获取DOM元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!