您的位置 >>> 星想互联 >>> 编程技术 >>> JQUERY+JS
JS面向对象实例---拖拽
点击数:1655  发布时间2018-06-23 19:37:52
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>
div {
position: absolute;
}
</style>
<title>拖拽</title>
<script type="text/javascript" >
/**
* 拖拽
* @param {Object} id div的id
*/
function Drag(id){
this.oBox = document.getElementById(id);
this.disX = 0;
this.disY = 0;
var _this = this;
this.oBox.onmousedown = function(){
_this.fnDown();
}
}
//鼠标按下
Drag.prototype.fnDown = function(ev){
var oEvent = ev || event;
this.disX = oEvent.clientX - this.oBox.offsetLeft;
this.disY = oEvent.clientY - this.oBox.offsetTop;
var _this = this;
document.onmousemove = function(){
_this.fnMove();
};
document.onmouseup = function(){
_this.fnUp();
};
}
//鼠标移动
Drag.prototype.fnMove = function(ev){
var oEvent= ev || event;
this.oBox.style.left = oEvent.clientX - this.disX + 'px';
this.oBox.style.top = oEvent.clientY - this.disY + 'px';
}
//鼠标抬起
Drag.prototype.fnUp = function(){
document.onmousemove = null;
document.onmouseup = null;
}

</script>
<script>
window.onload = function(){
var drag1 = new Drag("box1");
var drag1 = new Drag("box2");
};
</script>
</head>

<body>
<div id="box1" style="background: red;width: 200px;height: 200px;"></div>
<div id="box2" style="background: blue;width: 100px;height: 300px;"></div>
</body>
</html>
来源:咸宁网站建设