项目要求
使用JS实现鼠标拖拽效果
代码演示
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
#box{
position: absolute;
width: 400px;
height: 300px;
background-color: #ff0000;
}
</style>
</head>
<body>
<div id="box"></div>
<script>
//获取box标签
let box = document.getElementById("box");
//鼠标左键按下进行拖动
box.onmousedown = function(e){
//记录鼠标在div上的位置
let offsetLeftX = e.clientX
let offsetTopY = e.clientY
//鼠标在窗口中移动
document.onmousemove = function(e2){
//计算鼠标在窗口中的位置
let clientX = e2.clientX
let clientY = e2.clientY
console.log(clientX,"clientX")
console.log(clientY,"clientY")
//计算div的位置
_left = clientX - offsetLeftX
_top = clientY - offsetTopY
console.log(_left,"left")
console.log(_top,"top")
//左边界判断
if(_left < 0){
_left = 0
}
//右边界判断
if(_left > document.documentElement.clientWidth - box.offsetWidth){
_left = document.documentElement.clientWidth - box.offsetWidth
}
//上边界判断
if(_top < 0){
_top = 0
}
//下边界判断
if(_top > document.documentElement.clientHeight - box.offsetHeight){
_top = document.documentElement.clientHeight - box.offsetHeight
}
//定位div的位置
box.style.left = _left + "px"
box.style.top = _top + "px"
}
}
//鼠标抬起
box.onmouseup = function(){
//停止拖动
document.onmousemove = null
}
</script>
</body>
</html>
效果演示

由于跟随鼠标,图片效果不明显