实现拖拽,必须使用到三个事件,并且这三个事件的使用顺序不能颠倒。
onmouseover:鼠标按下事件
onmousemove:鼠标移动事件
onmouseup:鼠标抬起事件
注意点:
元素一点要绝对定位,只有脱离文档流才能移动。
绑定拖拽的元素,移动事件和抬起事件是对document的绑定。
附代码:
<body>
<div id="box" onclick="handle()">
导航
</div>
</body>
<style>
body{
height: 95vh;
}
#box {
width: 50px;
height: 80px;
line-height: 80px;
color: #fff;
text-align: center;
background-color: #18900f;
position: absolute;
top: 300px;
right: 30px;
z-index: 1;
}
</style>
<script>
// 获取要拖拽的元素
var box = document.getElementById('box')
// 触发元素拖拽事件开关
var isMove = false
// 初始化坐标
var x = y = t = l = 0;
// 元素点击事件
box.onmousedown = function (e) {
// 获取x、y的坐标
x = e.clientX
y = e.clientY
// 获取左边和顶部的偏移量
l = box.offsetLeft
t = box.offsetTop
// 更改元素鼠标样式为拖拽鼠标
box.style.cursor = 'move'
// 触发元素拖拽事件开关
isMove = true
}
// 这里需要给document设定鼠标移动事件,不可以设给元素本身。否则会出现拖动过快鼠标丢失
document.onmousemove = function (e) {
// 判断是否触发事件,如果没有则不执行
if (!isMove) {
return
}
//获取x和y
var newX = e.clientX
var newY = e.clientY
//计算移动后的左偏移量和顶部的偏移量
var newL = newX - (x - l)
var newT = newY - (y - t)
// 控制偏移量不让它超出页面
if (newL < 0) {
box.style.left = '0px'
} else if (newL > document.body.clientWidth - 85) {
box.style.left = document.body.clientWidth - 85 + 'px'
} else {
box.style.left = newL + 'px'
}
if (newT < 0) {
box.style.top = '0px'
} else if (newT > document.body.clientHeight - 85) {
box.style.top = document.body.clientHeight - 85 + 'px'
} else {
box.style.top = newT + 'px'
}
}
document.onmouseup = function () {
// 关闭开关
isMove = false
// 鼠标样式恢复
box.style.cursor = 'default'
}
function handle() {
box.style.backgroundColor = '1890ff'
}
</script>版权声明:本文为weixin_50539469原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。