在javascript中选择区域/矩形 [英] Select area/rectangle in javascript

查看:123
本文介绍了在javascript中选择区域/矩形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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..

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

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

是否有任何现成的东西在带有虚线轮廓的区域上绘制透明div?

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

或者简单的实施。我可能花了几个小时才敲出一些东西,但我很惊讶没有什么可以让我在5分钟内完成它。

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.

推荐答案

看起来很简单......

Seems simple enough…

创建一个最初隐藏的div:

Create a div that's initially hidden:

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

样式:

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

和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/

这篇关于在javascript中选择区域/矩形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆