您的位置:首页 > Web前端 > JavaScript

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

2017-04-21 20:59 120 查看
先上效果:



<!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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  js 面向对象 拖拽