<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>拖拽</title>
<style type="text/css">
div{
width: 200px;
height: 200px;
background: red;
position: absolute;
top: 100px;
left: 100px;
cursor: move;
}
</style>
</head>
<body>
<div id="box"></div>
</body>
<script type="text/javascript">
/*var box=document.getElementById('box');
box.onmousedown=function(e){
var dix=e.clientX-this.offsetLeft;
var diy=e.clientY-this.offsetTop;
e.preventDefault();
document.onmousemove=function(e){
var dix2=e.clientX-dix;
var diy2=e.clientY-diy;
box.style.left=dix2+'px';
box.style.top=diy2+'px';
};
document.onmouseup=function(){
document.onmousedown=document.onmousemove=null;
}
}*/
/*
*面向对象方法
*/
/*变形:
1.尽量不要有函数的嵌套。
2.可以有全局变量;
3.把onload里面不是赋值的语句放到函数中;
修改:
1.全局变量就是属性;
2.函数就是方法;
3.onload中创建对象实例;
4.改this的指向
*/
//构造函数
function Tab(id){
this.box=document.getElementById(id);
this.dix=0;
this.diy=0;
this.inset();
}
//原型
Tab.prototype.inset=function(){
var _this=this;
this.box.onmousedown=function(e){
var e=e||window.event;
_this.down(e);
};
}
Tab.prototype.down=function(e){
var _this=this;
this.dix=e.clientX-this.box.offsetLeft;
this.diy=e.clientY-this.box.offsetTop;
// e.preventDefault();
document.onmousemove = function(ev){
var e=ev||window.event;
_this.move(e);
};
document.onmouseup=function(){
_this.up();
}
}
Tab.prototype.move=function(e){
this.box.style.left=e.clientX-this.dix+'px';
this.box.style.top=e.clientY-this.diy+'px';
}
Tab.prototype.up=function(){
document.onmousedown=document.onmousemove=null;
}
//实例
var b=new Tab('box');
b.inset();
</script>
</html>
面向对象写拖拽事件
最新推荐文章于 2021-12-01 21:24:24 发布