4

我需要在 Javascript 中实现从选定区域获取元素。这是在 chrome 应用程序中创建更好的、类似桌面的 UI 所必需的。最近的例子是在 Imgur 扩展中选择区域:

截屏

所以问题是:

  1. 如何在 javascript 中完成此选择?
  2. 如何从此选择中获取元素?
4

2 回答 2

4

我发现这很有趣,所以我使用 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();
});
于 2011-08-14T22:13:10.250 回答
-3

一旦您单击按钮,此代码将使您从文本区域中进行选择。

<script language=javascript>
function getSelText()
{
    var txt = '';
     if (window.getSelection)
    {
        txt = window.getSelection();
             }
    else if (document.getSelection)
    {
        txt = document.getSelection();
            }
    else if (document.selection)
    {
        txt = document.selection.createRange().text;
            }
    else return;
document.aform.selectedtext.value =  txt;
}
</script>
<input type="button" value="Get selection" onmousedown="getSelText()"> 
<form name=aform >
<textarea name="selectedtext" rows="5" cols="20"></textarea>
</form>
于 2011-08-14T07:42:01.610 回答