当前位置:编程学习 > JS >>

如何编写一个js,适用于所有浏览器可用鼠标在页面移动的DIV层?

答案:<!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=gb2312" /> <title>无标题文档</title> <script type="text/javascript" > String.prototype.getPxNumber=function(){ return Number(this.substr(0,(this.length-2))); }//扩展字符串对象的方法。。可以把n px中的n以数字的形式返回。 function $(id){ return document.getElementById(id); } var dragControll={ oldMouseX:0, oldMouseY:0, oldObjectX:0, oldObjectY:0, dragTarget:null, record:function(id,msg) { $(id).innerHTML=msg; }, startMove:function(evt) { this.recordPosition(evt); }, endMove:function(evt) { this.recordPosition(evt); this.dragTarget=null; }, recordPosition:function(evt) { var eventHappen=window.event ? window.event:evt; this.dragTarget=eventHappen.target ? eventHappen.target:evenHappen.srcElement; this.oldMouseX=eventHappen.clientX; this.oldMouseY=eventHappen.clientY; this.oldObjectX=this.dragTarget.style.left.getPxNumber(); this.oldObjectY=this.dragTarget.style.top.getPxNumber(); this.record("recordSpan","MouseX:"+this.oldMouseX+" MouseY:"+this.oldMouseY+" dragTargetX:"+this.oldObjectX+" dragTargetY:"+this.oldObjectY); }, moving: function(evt){ var eventHappen=window.event ? window.event:evt; var movingTarget=eventHappen.target ? eventHappen.target:eventHappen.srcElement; if(movingTarget==this.dragTarget){ movingTarget.style.left=String(this.oldObjectX+eventHappen.clientX-this.oldMouseX)+"px"; movingTarget.style.top=String(this.oldObjectY+eventHappen.clientY-this.oldMouseY)+"px"; //alert("!"); } } } </script> </head> <body> <div> <span id="recordSpan">recording...</span> </div> <div style="height:100px; width:100px; background-color:#00CC00; top:100px;left:100px; position:absolute" onmousedown="dragControll.startMove(event)" onmouseup="dragControll.endMove(event)" onmousemove="dragControll.moving(event)" ></div> </body> </html> 。。。 刚写的,试试。
其他:去搜搜 jquery  div拖动插件吧,有很多现成的实例,而且兼容性很好的,不需要自己写! JQ语言库可以实现

去www.w3scholl.com.cn去看一下吧,有教程

上一个:js或jquery定位光标
下一个:js验证后,取消文本框中的光标?

CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,