前言:很多时候,我们业务中需要对鼠标点击的元素进行拖拽,使用原生JS实现这个方法,主要用到鼠标事件和监听。
- onmousedown:鼠标按下事件
- onmousemove:鼠标移动事件
- onmouseup:鼠标抬起事件
注意:
- 被拖拽的元素一定要是绝对定位,脱离文档流才可以移动
- 绑定拖拽的元素,移动和鼠标松开后是对document的绑定,因为移动的是整个div。
实现思路
- 先获取被拖拽元素所能移动的最大距离,超过这个距离就移动不了
- 给元素的onmousedown绑定一个function(e)事件
- 获取鼠标按下的原点距离盒子边缘的距离diffX和diffY
- 设置onmousemove事件,将被拖拽元素的left和top设置
- left的值是拖拽之后的那个位置的鼠标的x值减去diffX
- top的值是拖拽之后的那个位置的鼠标的y值减去diffY
- 设置鼠标松开事件onmouseup
html
<body>
<div class="box">
<!-- 禁止图片拖拽打开新页面 -->
<img src="https://tvax4.sinaimg.cn/large/ec43126fgy1gzp7qtgjs0j213a1jlnpd.jpg" alt="" ondragstart="return false">
</div>
</body>
</html>
<style>
/* 一定要绝对定位 */
.box{
width: 150px;
position: absolute;
}
.box img{
width: 100%;
position: absolute;
}
</style>
<script>
// 获取盒子元素
var box = document.querySelector('.box')
// 获取元素最大能移动到的距离
var maxLeft = window.innerWidth - box.offsetWidth;
var maxTop = window.innerHeight - box.offsetHeight;
// 鼠标按下盒子事件
box.onmousedown = function(e){
e = e || window.event
// 获取鼠标按下的原点距离盒子边缘的距离
let diffX = e.clientX - box.offsetLeft
let diffY = e.clientY - box.offsetTop
// 鼠标移动
box.onmousemove = function(e){
e = e || window.event
// 移动之后记下鼠标在按下时的位置
let x = e.clientX - diffX
let y = e.clientY - diffY
// 限定元素只能在浏览器可视窗口内移动
x = x < 0 ? 0 : x > maxLeft ? maxLeft : x
y = y < 0 ? 0 : y > maxTop ? maxTop : y
box.style.left = x + 'px';
box.style.top = y + 'px';
}
box.onmouseup = function(e){
this.onmousemove = null
this.onmouseup = null
}
}
</script>
实现效果
目录