<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
div {
width: 100px;
height: 100px;
background: red;
position: absolute;
}
#div2 {
background: yellow;
}
</style>
</head>
<body>
<div id="div1"></div>
<div id="div2"></div>
<script>
//拖拽方法
function Drag(id) {
this.disX = 0; //默认坐标
this.disY = 0;
this.elem = document.getElementById(id); //获取传入进来的id
}
//初始化方法
Drag.prototype.init = function () {
var This = this; //指向实例化对象
this.elem.onmousedown = function (ev) { //对应的id元素事件
This.fnDown(ev);
document.onmousemove = function (ev) { //在对应的id元素事件中使用页面鼠标移动事件
This.fnMove(ev);
}
document.onmouseup = function () {
This.fnUp();
}
return false;
}
}
//移动过程 获得鼠标当前坐标,减掉方块距离页面最左边的距离,获得鼠标距离方块左边的距离,然后修改方块的定位,定位等于鼠标当前坐标减去鼠标距离方块左边的距离
//例如 鼠标当前坐标x120,方块距离页面左边20,鼠标就距离方块左边100,120-20=100,那么方块此时的left就为120-100=20px
Drag.prototype.fnDown = function (ev) {
//鼠标距离方块左边的值 = 鼠标当前位置 减去 方块距离左边的值
this.disX = ev.pageX - this.elem.offsetLeft;
this.disY = ev.pageY - this.elem.offsetTop;
}
Drag.prototype.fnMove = function (ev) {
//修改方块的位置 = 鼠标当前位置 减去 鼠标距离方块左边的值
this.elem.style.left = ev.pageX - this.disX + 'px';
this.elem.style.top = ev.pageY - this.disY + 'px';
}
Drag.prototype.fnUp = function () {
document.onmousemove = null;
document.onmouseup = null;
}
var d1 = new Drag('div1');
d1.init();
var d2 = new Drag('div2');
d2.init()
</script>
</body>
</html>
原生JS实现div方块拖拽
最新推荐文章于 2024-05-01 12:01:29 发布