console
<!DOCTYPE html>
<html>
<head>
<meta charset="gb2312" />
<title></title>
<style type="text/css">
.box {
background: #f00;
width: 0px;
height: 0px;
position: absolute;
opacity: 0.5;
cursor: move;
}
</style>
<script type="text/javascript">
window.onload = function(e) {
e = e || window.event;
var startX, startY, diffX, diffY;
var dragging = false;
document.onmousedown = function(e) {
startX = e.pageX;
startY = e.pageY;
if(e.target.className.match(/box/)) {
dragging = true;
if(document.getElementById("moving_box") !== null) {
document.getElementById("moving_box").removeAttribute("id");
}
e.target.id = "moving_box";
diffX = startX - e.target.offsetLeft;
diffY = startY - e.target.offsetTop;
}
else {
var active_box = document.createElement("div");
active_box.id = "active_box";
active_box.className = "box";
active_box.style.top = startY + 'px';
active_box.style.left = startX + 'px';
document.body.appendChild(active_box);
active_box = null;
}
};
document.onmousemove = function(e) {
if(document.getElementById("active_box") !== null) {
var ab = document.getElementById("active_box");
ab.style.width = e.pageX - startX + 'px';
ab.style.height = e.pageY - startY + 'px';
}
if(document.getElementById("moving_box") !== null && dragging) {
var mb = document.getElementById("moving_box");
mb.style.top = e.pageY - diffY + 'px';
mb.style.left = e.pageX - diffX + 'px';
}
};
document.onmouseup = function(e) {
dragging = false;
if(document.getElementById("active_box") !== null) {
var ab = document.getElementById("active_box");
ab.removeAttribute("id");
if(ab.offsetWidth < 3 || ab.offsetHeight < 3) {
document.body.removeChild(ab);
}
}
};
};
</script>
</head>
<body>
<p>点击鼠标左键并拖动绘制矩形</p>
</body>
</html>