用面向对象写程序之“完美”拖拽

先上效果:


<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>面向对象写“完美”拖拽</title>
<style>
* {
margin: 0;
padding: 0
}

#box {
width: 200px;
height: 200px;
background: red;
position: absolute;
}

#shadowBox {
width: 200px;
height: 200px;
border: 1px black dashed;
position: absolute;
box-sizing: border-box;
}
</style>
<script>
window.onload = function() {
new Gz();
}


function Gz() {
this.boxlf;
this.boxtp;
this.bjxj;
this.bjyj;
this.x;
this.y;
this.bjx;
this.bjy;
var that = this;
this.box = document.getElementById("box");
this.box.onmousedown = function(ev) {
that.down(ev);
}
}
Gz.prototype.down = function(ev) {
var that = this;
this.e = ev || event;
this.x = this.e.clientX - this.box.offsetLeft;
this.y = this.e.clientY - this.box.offsetTop;
this.shadowBox = document.createElement("div");
this.shadowBox.id = 'shadowBox';
document.body.appendChild(this.shadowBox);
document.onmousemove = function(ev) {
that.move(ev);
}
document.onmouseup = function() {
that.up();
}
return false; //这里阻止浏览器默认事件;
}
Gz.prototype.move = function(ev) {
this.e = ev || event;
this.boxlf = this.e.clientX - this.x;
this.boxtp = this.e.clientY - this.y;


this.bjxj = document.documentElement.clientWidth || document.body.clientWidth;
this.bjyj = document.documentElement.clientHeight || document.body.clientHeight;
this.bjx = this.bjxj - this.shadowBox.offsetWidth;
this.bjy = this.bjyj - this.shadowBox.offsetHeight;
if(this.boxlf < 0) {
this.boxlf = 0;
} else if(this.boxlf > this.bjx) {
this.boxlf = this.bjx
}
if(this.boxtp < 0) {
this.boxtp = 0;
} else if(this.boxtp > this.bjy) {
this.boxtp = this.bjy
}


this.shadowBox.style.left = this.boxlf + 'px';
this.shadowBox.style.top = this.boxtp + 'px';
}
Gz.prototype.up = function() {
this.box.style.left = this.shadowBox.offsetLeft + 'px';
this.box.style.top = this.shadowBox.offsetTop + 'px';
document.body.removeChild(this.shadowBox);
document.onmousemove = null;
document.onmouseup = null; //此拖拽并未兼容ie6 如果需要兼容 可以使用事件捕获、阻止;
}
</script>
</head>


<body>
<div id="box"></div>
</body>


</html>


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值