拖拽效果
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
#div {
width: 100px;
height: 100px;
background: red;
border-radius: 50%;
position: absolute;
z-index: 1;
}
#div1 {
width: 100px;
height: 100px;
background: blue;
border-radius: 50%;
position: absolute;
left: 100px;
top: 100px;
z-index: 0;
}
</style>
<script type="text/javascript">
window.onload = function() {
var div = document.getElementById("div");
div.onmousedown = function(ev) {
var e = window.event || ev
//獲取鼠標點擊的位置距離div左側(cè)和頂部邊框的間隔值
var oX = e.clientX - div.offsetLeft;
var oy = e.clientY - div.offsetTop;
//當鼠標移動榜苫,獲取到鼠標的偏移量把偏移量賦給標簽
document.onmousemove = function(ev) {
//計算出鼠標在X Y方向上移動的偏移量辛辨,把這個偏移量添加在標簽的左側(cè)和右側(cè)篡殷,就能實現(xiàn)標簽隨著鼠標移動
var e = window.event || ev
div.style.left = e.clientX - oX + "px";
div.style.top = e.clientY - oy + "PX"
}
//當鼠標抬起最爬,清除鼠標的移動事件
document.onmouseup = function() {
document.onmousemove = null;
document.onmouseup = null;
div = document.getElementById("div")
div.style.background = "black"
}
}
var div1 = document.getElementById("div1");
div1.onmousedown = function(ev) {
var e = window.event || ev
//獲取鼠標點擊的位置距離div左側(cè)和頂部邊框的間隔值
var oX = e.clientX - div1.offsetLeft;
var oy = e.clientY - div1.offsetTop;
//當鼠標移動,獲取到鼠標的偏移量把偏移量賦給標簽
document.onmousemove = function(ev) {
//計算出鼠標在X Y方向上移動的偏移量但骨,把這個偏移量添加在標簽的左側(cè)和右側(cè)卸勺,就能實現(xiàn)標簽隨著鼠標移動
var e = window.event || ev
div1.style.left = e.clientX - oX + "px";
div1.style.top = e.clientY - oy + "PX"
}
//當鼠標抬起,清除鼠標的移動事件
document.onmouseup = function() {
document.onmousemove = null;
document.onmouseup = null;
div1 =document.getElementById("div1")
div1.style.background = "yellow"
}
}
}
</script>
</head>
<body>
<div id="div"></div>
<div id="div1"></div>
</body>
</html>來源: http://10.0.88.88:8083/forum.php?mod=viewthread&tid=43756