js鼠标拖拽元素
//假设想在元素的范围内拖拽元素 那么就可以给移动的距离设置限度
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
#box {
position: absolute;
left: 0;
top: 0;
width: 100px;
height: 100px;
background-color: #f00;
}
</style>
</head>
<body>
<div id="box"></div>
<script>
var box = document.getElementById('box');
box.addEventListener('mousedown', function(e) {
var firstX = e.clientX;//获得鼠标点击的位置
var firstY = e.clientY;
var nowX = box.offsetLeft;//获得div即移动方块的初始位置
var nowY = box.offsetTop;
document.onmousemove = function(e) {
//更改元素的位置:初始的位置 +鼠标的位置-鼠标在元素内的位置
box.style.left = nowX + e.clientX - firstX + 'px';
box.style.top = nowY + e.clientY - firstY + 'px';
console.log(1);
}
})
//当鼠标按键放开的时候 将鼠标移动事件置为空
box.addEventListener('mouseup', function() {
document.onmousemove = null
})
</script>
</body>
</html>