JavaScript实现元素拖拽功能
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
* {
padding: 0px;
height: 0px;
}
#dragBox {
width: 200px;
height: 200px;
background-color: aquamarine;
position: relative;
}
</style>
<body>
<div id="dragBox"></div>
<script>
var position = {
// 用于记录鼠标的原始位置及实时位置
oldX: 0,
oldY: 0,
newX: 0,
newY: 0,
// 用于记录需要拖动的div当前位置
divX: 0,
divY: 0
}, tag = 0;
var getBox = document.querySelector("#dragBox");
document.addEventListener('mousedown', function () {
// 获取鼠标按下时初始位置位置
var e = e || window.event;
position.oldX = e.pageX;
position.oldY = e.pageY;
tag = 1;
})
document.addEventListener('mousemove', function () {
if (tag === 1) {
var e = e || window.event;
position.newX = e.pageX;
position.newY = e.pageY;
getBox.style.left = position.newX - position.oldX+position.divX + 'px';
getBox.style.top = position.newY - position.oldY +position.divY+ 'px';
}
})
document.addEventListener('mouseup',function(){
tag = 0;
position.divX = position.newX - position.oldX+position.divX ;
position.divY = position.newY - position.oldY+position.divY;
})
</script>
</body>
</html>
效果演示