<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
#box1{
width: 100px;
height: 100px;
background-color: red;
position: absolute;
}
#box2{
width: 100px;
height: 100px;
background-color: yellow;
position: absolute;
left: 200px;
top: 200px;
}
</style>
<script type="text/javascript">
window.onload = function(){
/*
* 拖拽box1元素
* - 拖拽的流程
* 1.當鼠標在被拖拽元素上按下時,開始拖拽 onmousedown
* 2.當鼠標移動時被拖拽元素跟隨鼠標移動 onmousemove
* 3.當鼠標松開時,被拖拽元素固定在當前位置 onmouseup
*/
//獲取box1
var box1 = document.getElementById("box1");
//為box1綁定一個鼠標按下事件
//當鼠標在被拖拽元素上按下時,開始拖拽 onmousedown
box1.onmousedown = function(event){
event = event || window.event;
//div的偏移量 鼠標.clentX - 元素.offsetLeft
//div的偏移量 鼠標.clentY - 元素.offsetTop
var ol = event.clientX - box1.offsetLeft;
var ot = event.clientY - box1.offsetTop;
//為document綁定一個onmousemove事件
document.onmousemove = function(event){
event = event || window.event;
//當鼠標移動時被拖拽元素跟隨鼠標移動 onmousemove
//獲取鼠標的坐標
var left = event.clientX - ol;
var top = event.clientY - ot;
//修改box1的位置
box1.style.left = left+"px";
box1.style.top = top+"px";
};
//為document綁定一個鼠標松開事件
document.onmouseup = function(){
//當鼠標松開時,被拖拽元素固定在當前位置 onmouseup
//取消document的onmousemove事件
document.onmousemove = null;
//取消document的onmouseup事件
document.onmouseup = null;
};
};
};
</script>
</head>
<body>
<div id="box1"></div>
<div id="box2"></div>
</body>
</html>
鼠標拖拽1
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
推薦閱讀更多精彩內容
- 思路: 利用onmousedown事件實現拖拽。首先獲得鼠標橫坐標點和縱坐標點到div的距離,然后當鼠標移動后再用...