<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style type="text/css">
#box1{
width: 100px;
height: 100px;
background-color: red;
position: absolute;
}
</style>
<script type="text/javascript">
window.onload = function(){
/*
1.鼠标在拖拽元素上按下时,开始拖拽onmousedown
2.移动鼠标被拖拽元素跟随鼠标移动onmousemove
3.鼠标松开,被拖拽元素固定 onmouseup
*/
var box1 = document.getElementById("box1");
box1.onmousedown = function(event){
//div的偏移量 鼠标.clentX - 元素.offsetLeft
//div的偏移量 鼠标.clentY - 元素.offsetTop
var ol = event.clientX - box1.offsetLeft;
var ot = event.clientY - box1.offsetTop;
document.onmousemove = function(event){
var left = event.clientX - ol;
var top = event.clientY - ot;
box1.style.left = left+"px";
box1.style.top = top+"px";
}
document.onmouseup = function(){
//取消onmousemove方法
document.onmousemove = null;
//取消onmouseup方法
document.onmouseup = null;
};
};
}
</script>
</head>
<body>
<div id="box1"></div>
</body>
</html>
div随鼠标拖拽
最新推荐文章于 2022-10-26 09:14:31 发布