js特效 拖拽
js 特效 拖拽
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
#div{
width: 100px;
height: 100px;
background-color: blue;
position:absolute;
top: 20px;
left: 300px;
}
</style>
</head>
<body>
<div id = "div"></div>
<script type="text/javascript">
var muvDiv = document.getElementById('div');
muvDiv.onmousedown = function(){
// 1.鼠标位置减去盒子位置,获取差值
var ol = event.clientX - muvDiv.offsetLeft;
var ot = event.clientY - muvDiv.offsetTop;
document.onmousemove = function(){
var event = event || window.event;
// 2.获取当前鼠标位置,减去差值,求出准确位置
var top = event.clientY - ot;
var left = event.clientX - ol;
// 3.给css获取新值
muvDiv.style.top = top + 'px';
muvDiv.style.left = left + 'px';
}
}
// 4.清除onmousemove函数
document.onmouseup = function(){
document.onmousemove = null;
}
</script>
</body>
</html>