js小案例:实现元素的拖拽功能
实现拖拽,必须使用到三个事件,并且这三个事件的使用顺序不能颠倒。
- onmouseover:鼠标按下事件
- onmousemove:鼠标移动事件
- onmouseup:鼠标抬起事件
注意点:
- 元素一点要绝对定位,只有脱离文档流才能移动。
- 绑定拖拽的元素,移动事件和抬起事件是对document的绑定。
基本思路:
1、点击
*a: 获取当前鼠标坐标(X轴和Y轴)
*b: 获取需要拖拽的元素到浏览器的距离(上边距和左边距)
*c=a-b:得到鼠标当前在需要拖拽的元素的内部距离
2、移动
通过a-c建立鼠标与拖拽元素的关系,防止鼠标超出拖拽元素。
贴上代码
html部分
<div id="box"></div>
css部分
#box {
width: 200px;
height: 100px;
position: absolute;
top: 30px;
left: 30px;
background-color: pink;
}
js部分
<script>
window.onload = function () {
box.onmousedown = function () {
var needX = event.clientX - this.offsetLeft;
var needY = event.clientY - this.offsetTop;
var _this = this;//存放当前的this
document.onmousemove = function () {
_this.style.left = event.clientX - needX + 'px';
_this.style.top = event.clientY - needY + 'px';
}
document.onmouseup = function () {
this.onmouseup = this.onmousemove = null;
}
}
}
</script>
版权声明:本文为weixin_45792701原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。