<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
#red{
width:100px;
height:100px;
background:red;
position: absolute;
}
</style>
</head>
<body>
<div id="red"></div>
<script>
let red = document.getElementById('red')
red.onmousedown = function (e1){
red.style.border = '3px solid blue'
document.onmousemove=function (e2){
// 当鼠标移动时,将当前鼠标相对视口的坐标赋值给元素的left和top
// 因为我们需要在按下的位置拖拽,因此我们还需要获取按下键鼠标相对div的左上角位置
// 使用当前鼠标位置减去这个相对元素的左上角位置,保证鼠标所按位置拖拽
red.style.left=e2.clientX - e1.offsetX + 'px'
red.style.top=e2.clientY - e1.offsetY + 'px'
}
// 当释放鼠标键时,删除鼠标移动事件和删除鼠标释放事件
document.onmouseup=function(){
document.onmousemove=null;
document.onmouseup=null;
red.style.borderStyle = ''
red.style.borderColor = ''
red.style.borderWidth = ''
}
}
</script>
</body>
</html>
js拖拽功能的实现
最新推荐文章于 2023-11-28 11:58:47 发布