浏览 3624 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
|
|
---|---|
作者 | 正文 |
发表时间:2008-08-11
实现div拖动效果,在设置和取left和top值时,各种浏览器的js实现不同,把变化封装到接口 MyAPI 的三个方法:getTop(), getLeft(), moveTo()中, 在对各种浏览器写具体实现类,如下图 UML图: 在Javascript中 用 MyAPI 对IEAPI 和 W3CAPI 和聚合关系("has-a") 摸似了继承关系,代码如下(myapi.js): //Interface function MyAPI() { this.Type = {// mark web browser ---------- learn from prototype framework IE: !!(window.attachEvent && !window.opera), Opera: !!window.opera, WebKit: navigator.userAgent.indexOf('AppleWebKit/') > -1, Gecko: navigator.userAgent.indexOf('Gecko') > -1 && navigator.userAgent.indexOf('KHTML') == -1, MobileSafari: !!navigator.userAgent.match(/Apple.*Mobile.*Safari/) } this.api = this.getInstance(); return this; } //IE implementation function IEAPI() { return this; } //W3C implementataion function W3CAPI() { return this; } //factory method MyAPI.prototype.getInstance=function() { if(this.Type.IE) return new IEAPI(); else return new W3CAPI(); }; //method moveTo detail implementation MyAPI.prototype.moveTo=function(obj,iX,iY) { this.api.moveTo(obj,iX,iY); } IEAPI.prototype.moveTo=function(obj,iX,iY) { if(iX!=null) obj.style.pixelLeft=iX; if(iY!=null) obj.style.pixelTop=iY; } W3CAPI.prototype.moveTo=function(obj,iX,iY) { if(iX!=null) obj.style.left=iX+"px"; if(iY!=null) obj.style.top=iY+"px"; } //method getLeft detail implementation MyAPI.prototype.getLeft=function(obj) { return this.api.getLeft(obj); } IEAPI.prototype.getLeft=function(obj) { return obj.style.pixelLeft; } W3CAPI.prototype.getLeft=function(obj) { return parseInt(obj.style.left); } //method getTop detail implementation MyAPI.prototype.getTop=function(obj) { return this.api.getTop(obj); } IEAPI.prototype.getTop=function(obj) { return obj.style.pixelTop; } W3CAPI.prototype.getTop=function(obj) { return parseInt(obj.style.top); } 2 用写好的API实现对Div的简单拖动效果 代码如下:(demo.html) <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>move demo</title> <script src="myapi.js" type="text/javascript"></script> <script language="javascript"> var myAPI = new MyAPI(); var moveable = false; var xOff = 0; var yOff = 0; function start(obj,e){ moveable = true; xOff = myAPI.getLeft(obj) - e.clientX; yOff = myAPI.getTop(obj) - e.clientY; } function move(obj,e){ if(moveable){ myAPI.moveTo(obj, xOff + e.clientX, yOff + e.clientY) } } function end(){ moveable = false; } </script> </head> <body> <div style="width:200px; height:200px; top:200px; left:200px; position:absolute; background:#CC99CC" onmousedown="start(this,event)" onmousemove="move(this,event)" onmouseup="end()"></div> </body> </html> 是简单拖动,只在IE6和FireFox2下测过,也没有对所有浏览器封装,还有一些bug 比如鼠标移动太快,拖出div 后,因为mouseup事件触发不了而出来div粘上鼠标情况,在 div 上加个mouseout="end()"更好些 (祝中国2008奥运会成功) 声明:ITeye文章版权属于作者,受法律保护。没有作者书面许可不得转载。
推荐链接
|
|
返回顶楼 | |