给大家分享一个用原生JS编写的拖拽及拖拽方法继承的 小Demo,代码如下。
代码语言:javascript复制<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>原生JS中的拖拽方法继承</title>
<style>
#div1 {
width: 100px;
height: 100px;
background: red;
position: absolute;
}
#div2 {
width: 100px;
height: 100px;
background: yellow;
position: absolute;
}
</style>
<script>
// 定义拖拽父级对象
function Drag(id) {
var that = this;
this.disX = 0;
this.disY = 0;
this.oDiv = document.getElementById(id);
this.oDiv.onmousedown = function (ev) {
that.fnDown(ev);
return false;
};
};
// 拖拽父级对象原型上添加鼠标落下时的方法
Drag.prototype.fnDown = function (ev) {
var that = this;
var oEvent = ev || event;
this.disX = oEvent.clientX - this.oDiv.offsetLeft;
this.disY = oEvent.clientY - this.oDiv.offsetTop;
document.onmousemove = function (ev) {
that.fnMove(ev);
};
document.onmouseup = function () {
that.fnUp();
};
};
// 拖拽父级对象原型上添加鼠标移动时的方法
Drag.prototype.fnMove = function (ev) {
var oEvent = ev || event;
this.oDiv.style.left = oEvent.clientX - this.disX 'px';
this.oDiv.style.top = oEvent.clientY - this.disY 'px';
};
// 拖拽父级对象原型上添加鼠标抬起时的方法
Drag.prototype.fnUp = function () {
document.onmousemove = null;
document.onmouseup = null;
};
</script>
<script>
// 拖拽子对象的方法
function LimitDrag(id) {
// 调用父级对象
Drag.call(this, id);
};
// 继承父级对象的原型
LimitDrag.prototype = Drag.prototype;
// 修改父级对象上拖拽鼠标移动时的方法,添加边界限制
LimitDrag.prototype.fnMove = function (ev) {
var oEvent = ev || event;
var l = oEvent.clientX - this.disX;
var t = oEvent.clientY - this.disY;
if (l < 0) {
l = 0;
} else if (l > document.documentElement.clientWidth - this.oDiv.offsetWidth) {
l = document.documentElement.clientWidth - this.oDiv.offsetWidth;
};
if (t < 0) {
t = 0;
} else if (t > document.documentElement.clientHeight - this.oDiv.offsetHeight) {
t = document.documentElement.clientHeight - this.oDiv.offsetHeight;
};
this.oDiv.style.left = l 'px';
this.oDiv.style.top = t 'px';
};
</script>
<script>
window.onload = function () {
// div1在拖动过程中没有边界限制
new Drag('div1');
// div2在拖动过程中通过将方法改写加上边界限制
new LimitDrag('div2');
};
</script>
</head>
<body>
<div id="div1"></div>
<div id="div2"></div>
</body>
</html>