前端开发的时候,有好多地方用到拖拽效果,当然 http://jqueryui.com/draggable/ 是个不错的选择,but 我是个打破砂锅问到底的人,抽点时间用js小小的实现了类似的插件,话不多说。
first: html和css
复制代码 代码如下:
now,先把主要算法实现一下:
复制代码 代码如下:
yeah,使用面向对象实现一下
复制代码 代码如下:
js draggle class:
复制代码 代码如下:
function drag(id) {
this.div = document.getelementbyid(id);
if (this.div) {
this.div.style.cursor = move;
this.div.style.position = absolute;
}
this.disx = 0;
this.disy = 0;
var _this = this;
this.div.onmousedown = function (evt) {
_this.getdistance(evt);
document.onmousemove = function (evt) {
_this.setposition(evt);
}
_this.div.onmouseup = function () {
_this.clearevent();
}
}
}
drag.prototype.getdistance = function (evt) {
var oevent = evt || event;
this.disx = oevent.clientx - this.div.offsetleft;
this.disy = oevent.clienty - this.div.offsettop;
}
drag.prototype.setposition = function (evt) {
var oevent = evt || event;
var l = oevent.clientx - this.disx;
var t = oevent.clienty - this.disy;
if (l l = 0;
}
else if (l >= document.documentelement.clientwidth - this.div.offsetwidth) {
l = document.documentelement.clientwidth - this.div.offsetwidth;
}
if (t t = 0;
}
else if (t >= document.documentelement.clientheight - this.div.offsetheight) {
t = document.documentelement.clientheight - this.div.offsetheight;
}
this.div.style.left = l + px;
this.div.style.top = t + px;
}
drag.prototype.clearevent = function () {
this.div.onmouseup = null;
document.onmousemove = null;
}
at last:最终实现:
复制代码 代码如下:
window.onload = function () {
new drag(div1);
new drag(div2);
}
效果如下:
以上所述就是本文的全部内容了,希望能对大家更加熟练的掌握javascript有所帮助。