我需要在
Javascript中实现从选定区域获取元素.这需要在chrome应用程序中创建更好的,类似桌面的UI.最近的例子是在Imgur扩展中选择区域:
所以问题是:
>如何在javascript中完成此选择?
>如何从这个选择中获取元素?
最佳答案 我发现这很有趣所以我使用jQuery从头开始制作东西,因为它会变得太复杂,否则:
http://jsfiddle.net/EuSBU/1/.
我希望它能够直截了当地跟随,请问你是否有想知道的事情.
它主要归结为检查矩形是否封装它的每个元素.
$("#start_select").click(function() {
$("#select_canvas").show();
});
$('*').bind('selectstart', false);
var start = null;
var ctx = $("#select_canvas").get(0).getContext('2d');
ctx.globalAlpha = 0.5;
$("#select_canvas").mousedown(function(e) {
start = [e.offsetX, e.offsetY];
}).mouseup(function(e) {
end = [e.offsetX, e.offsetY];
var x1 = Math.min(start[0], end[0]),
x2 = Math.max(start[0], end[0]),
y1 = Math.min(start[1], end[1]),
y2 = Math.max(start[1], end[1]);
var grabbed = [];
$('*').each(function() {
if(!$(this).is(":visible")) return;
var o = $(this).offset(),
x = o.left,
y = o.top,
w = $(this).width(),
h = $(this).height();
if(x > x1 && x + w < x2 && y > y1 && y + h < y2) {
grabbed.push(this);
}
});
console.log(grabbed);
start = null;
$(this).hide();
}).mousemove(function(e) {
if(!start) return;
ctx.clearRect(0, 0, this.offsetWidth, this.offsetHeight);
ctx.beginPath();
var x = e.offsetX,
y = e.offsetY;
ctx.rect(start[0], start[1], x - start[0], y - start[1]);
ctx.fill();
});