本文实例讲述了JS面向对象编程实现的拖拽功能。分享给大家供大家参考,具体如下:
原始的面向过程代码:
#box {
width: 100px;
height: 100px;
background: blue;
position: absolute;
}
拖拽
下面是面向对象的代码
drag.js
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;
}
drag.html
div {
position: absolute;
}
拖拽
此拖拽有一个问题,就是没有控制拖拽出边界的问题。但我们又不想去修改代码,那我们怎么做?学过java的应该都知道可以写一个子类来做一些更加具体的操作,又保留了父类的功能,就是继承。
html
DragLimit.js:DragLimit继承自Drag,控制了不能出边界
function DragLimit(id){
Drag.call(this, id);
}
//继承方法
for(var p in Drag.prototype){
DragLimit.prototype[p] = Drag.prototype[p];
}
DragLimit.prototype.fnMove = function(ev){
var oEvent= ev || event;
var left = oEvent.clientX - this.disX;
var top = oEvent.clientY - this.disY;
//控制边界
if(left < 0){
left = 0;
} else if(left > document.documentElement.clientWidth-this.oBox.offsetWidth){
left = document.documentElement.clientWidth-this.oBox.offsetWidth;
}
if(top <= 0){
top = 0;
} else if(top > document.documentElement.clientHeight-this.oBox.offsetHeight){
top = document.documentElement.clientHeight-this.oBox.offsetHeight;
}
this.oBox.style.left = left + 'px';
this.oBox.style.top = top + 'px';
}
感兴趣的朋友可以使用在线HTML/CSS/Javascript代码运行工具:http://tools.jb51.net/code/HtmlJsRun测试上述代码运行效果。
更多关于Javascript相关内容感兴趣的读者可查看本站专题:《javascript面向对象入门教程》、《Javascript错误与调试技巧总结》、《Javascript数据结构与算法技巧总结》、《Javascript遍历算法与技巧总结》及《Javascript数学运算用法总结》
希望本文所述对大家Javascript程序设计有所帮助。



