javascript 在javascript中选择区域/矩形

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23284429/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 00:40:27  来源:igfitidea点击:

Select area/rectangle in javascript

javascriptjqueryjquery-ui

提问by burtonator

I need to select a region in an HTML5 page via the mouse.

我需要通过鼠标在 HTML5 页面中选择一个区域。

I'm then going to interact with the elements within that region.

然后我将与该区域内的元素进行交互。

There MUST be an easy way to do it but I couldn't find anything off the shelf..

必须有一种简单的方法来做到这一点,但我找不到现成的任何东西..

The jquery UI selection didn't work unfortunately because it seems to only support one parent element.

不幸的是,jquery UI 选择不起作用,因为它似乎只支持一个父元素。

Is there anything off the shelf to draw a transparent div over a region with a dashed outline?

有什么现成的东西可以在带有虚线轮廓的区域上绘制透明 div 吗?

Or an easy implementation. I could probably spend a couple of hours and bang something out but I'm surprised there's nothing that allows me to do it in 5 minutes.

或者一个简单的实现。我可能会花几个小时来完成一些事情,但我很惊讶没有什么可以让我在 5 分钟内完成。

回答by bjb568

Seems simple enough…

看起来很简单……

Create a div that's initially hidden:

创建一个最初隐藏的 div:

<div id="div" hidden></div>

Style it:

样式:

#div {
    border: 1px dotted #000;
    position: absolute;
}

And the JS:

和 JS:

var div = document.getElementById('div'), x1 = 0, y1 = 0, x2 = 0, y2 = 0;
function reCalc() { //This will restyle the div
    var x3 = Math.min(x1,x2); //Smaller X
    var x4 = Math.max(x1,x2); //Larger X
    var y3 = Math.min(y1,y2); //Smaller Y
    var y4 = Math.max(y1,y2); //Larger Y
    div.style.left = x3 + 'px';
    div.style.top = y3 + 'px';
    div.style.width = x4 - x3 + 'px';
    div.style.height = y4 - y3 + 'px';
}
onmousedown = function(e) {
    div.hidden = 0; //Unhide the div
    x1 = e.clientX; //Set the initial X
    y1 = e.clientY; //Set the initial Y
    reCalc();
};
onmousemove = function(e) {
    x2 = e.clientX; //Update the current position X
    y2 = e.clientY; //Update the current position Y
    reCalc();
};
onmouseup = function(e) {
    div.hidden = 1; //Hide the div
};

http://jsfiddle.net/jLqHv/

http://jsfiddle.net/jLqHv/

回答by Simon

I've created a library for exactly this purpose: https://github.com/Simonwep/selection

我为此目的创建了一个库:https: //github.com/Simonwep/selection

There's currently full desktop and mobile / touch support as well as auto-scroll functionality as you know from your file explorer :)

正如您从文件浏览器中了解到的,目前有完整的桌面和移动/触摸支持以及自动滚动功能:)