<!DOCTYPE html><html> <head> <meta charset="UTF-8"> <title></title> <style> #div2 { width: 150px; height: 150px; position: absolute; background: #CCCC ...
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style>
#div2 {
width: 150px;
height: 150px;
position: absolute;
background: #CCCCCC;
}
.box{
border: 1px dashed black;
position: absolute;
}
</style>
<script>
window.onload = function() {
var div2 = document.getElementById('div2');
var x = 0;
var y = 0;
document.onmousedown = function(ev) {
//獲取具有相容性的事件
var oEvent = ev || event;
//x、y分別代表,滑鼠與div之間的橫坐標和縱坐標
x = oEvent.clientX - div2.offsetLeft;
y = oEvent.clientY - div2.offsetTop;
//創建一個div元素
var box = document.createElement('div');
//將創建好的樣式賦給box
box.className = 'box';
//將div的長寬賦給box
box.style.width = div2.offsetWidth - 2 + 'px';
box.style.height = div2.offsetHeight - 2 + 'px';
//按下滑鼠,將div當前的位置賦給box,防止每次點擊時,虛線框都會在左上角閃一下
box.style.left = div2.offsetLeft + 'px';
box.style.top = div2.offsetTop + 'px';
//將box插入到頁面
document.body.appendChild(box);
//mouseMove函數
document.onmousemove = function(ev) {
var oEvent = ev || event;
//m、n分別代表div的橫、縱坐標
var m = oEvent.clientX - x;
var n = oEvent.clientY - y;
//設置div的坐標
box.style.left = m + 'px';
box.style.top = n + 'px';
};
//mouseUp函數
document.onmouseup = function(ev) {
var oEvent = ev || event;
//釋放move事件,如果不釋放,放開滑鼠後,div仍然會跟隨滑鼠移動
document.onmousemove = null;
document.onmouseup = null;
//放開滑鼠後,將虛線框的位置賦給div2
div2.style.left = box.offsetLeft + 'px';
div2.style.top = box.offsetTop + 'px';
//並且移出虛線框
document.body.removeChild(box);
}
return false;
};
};
</script>
</head>
<body>
<div id="div2"></div>
</body>
</html>