js拖拽功能实现
html代码
这个没什么好说的,就是几个框框,尤其注意一点的是一定要用position的绝对定位
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
*{
padding: 0;
margin: 0;
}
#div1{
width: 100px;
height: 100px;
background: gray;
position: absolute;
}
#div2{
width: 100px;
height: 100px;
background: orange;
position: absolute;
left: 100px;
}
#div3{
width: 100px;
height: 100px;
background: tomato;
position: absolute;
left: 200px;
}
</style>
<script src="drag.js"></script>
</head>
<body>
<div id="div1"></div>
<div id="div2"></div>
<div id="div3"></div>
</body>
</html>
js代码
window.onload = function(){
var d1 = new Drag()
d1.init('div1')
var d2 = new Drag()
d2.init('div2')
var d3 = new Drag()
d3.init('div3')
}
//下面采用的是ES6的class写法以及箭头函数的使用
class Drag{
//保存获取的标签元素
obj = null
//保存鼠标按下位置距离元素左边框的距离
disX = 0
//保存鼠标按下位置距离元素上边框的距离
disY = 0
//初始化拖拽效果
init(id){
this.obj = document.getElementById(id)
//当鼠标按下后执行
this.obj.onmousedown = ev => {
var ev = ev || window.event
//保存位置
this.toDown(ev)
//当鼠标移动时
document.onmousemove = ev => {
var ev = ev || window.event
//改变元素的原有样式,即位置属性
this.toMove(ev)
}
//当鼠标松开后
document.onmouseup = () =>{
this.toUp()
}
}
}
toDown(ev){
this.disX = ev.clientX - this.obj.offsetLeft
this.disY = ev.clientY - this.obj.offsetTop
}
toMove(ev){
this.obj.style.left = ev.clientX - this.disX + 'px'
this.obj.style.top = ev.clientY - this.disY + 'px'
this.obj.style.opacity = '0.5'
}
toUp(){
document.onmousemove = null
document.onmouseup = null
this.obj.style.opacity = '1'
}
}
- 其中值得注意的是onmousedown与onmouseup委托到document上面,为的是保证其鼠标移动的准确性。通过事件冒泡去捕获到这两种事件,从而达到事件委托
- 这里用ES6的箭头函数和class是为了避免this指针发生变化的情况