<html><head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="robots" content="noindex,nofollow">
<title>拖拽效果</title>
</head>
<style type="text/css">
body{
overflow: hidden;
}
#box{
width: 200px;
height: 200px;
background: lightblue;
cursor: move;
position: absolute;
top: 88px;
left:33px;
}
</style>
<body>
<div id="box"></div>
<script type="text/javascript">
var box = document.querySelectorAll('#box')[0]
box.addEventListener('mousedown', down)
// 获取当前视窗的宽度和高度,可自行更换实际容器的宽高
// 边界值需要减去盒子的宽高
let cw = document.documentElement.clientWidth - box.offsetWidth, ch = document.documentElement.clientHeight - box.offsetHeight
function down(e) {
//当前盒子距离容器的左偏移量
this.startL = this.offsetLeft
//当前盒子距离容器的上偏移量
this.startT = this.offsetTop
//鼠标按下时的位置
this.startX = e.clientX
this.startY = e.clientY
//使用bind改变this指向,使其指向box
this.move = move.bind(this)
this.up = up.bind(this)
//鼠标按下后给document绑定mousemove以及mouseup事件
document.addEventListener('mousemove', this.move)
document.addEventListener('mouseup', this.up)
}
function move(e) {
// 定义变量:用当前鼠标的位置 - 初始的鼠标位置 + 盒子的宽度/高度
let curL = e.clientX - this.startX +this.startL,
curT = e.clientY - this.startY +this.startT
// 边界值判断
curL = curL < 0 ? 0 : (curL > cw ? cw : curL)
curT = curT < 0 ? 0 : (curT > ch ? ch : curT)
this.style.cssText = `top:${curT}px;left:${curL}px`
}
function up(e) {
//鼠标抬起,document解绑事件
document.removeEventListener('mousemove', this.move)
document.removeEventListener('mouseup', this.up)
}
</script>
</body>
</html>
以上代码复制粘贴就可以用,可以实现简单的拖拽效果