您的位置:首页 > 其它

获取鼠标的坐标,获取控件的坐标

2007-10-30 18:29 176 查看
1.获取html控件的位置

在网上很多人都会回答两种错误的方法 

错误方法一:

function showListMenu(ev){
     var T=ev.offsetTop; var T=ev.offsetLeft; 
   alert("控件"+ev+"的X坐标:"+L);
  alert("控件"+ev+"的Y坐标:"+T);     

  }

错误方法二:

function showListMenu(ev){
     var T=ev.style.top; var L=ev.style.left; 
   alert("控件"+ev+"的X坐标:"+L);
  alert("控件"+ev+"的Y坐标:"+T);     

  }

错误原因都是没有理解获取控件坐标的原理,所以都直接套用了方法,于是获取的时候就得到错误数据

正确方法如下:

function showListMenu(ev){
       var t=ev.offsetTop; var l=ev.offsetLeft;
        while(ev=ev.offsetParent)
        {
         t+=ev.offsetTop;
         l+=ev.offsetLeft;
        } 
       alert("控件"+ev+"的X坐标:"+x);
      alert("控件"+ev+"的Y坐标:"+t);     
  }

希望对大家有些帮助!!!!!

一,获取鼠标的坐标。
           IE,firefox下获取鼠标的方法不同,原因是:IE中event是全局变量,会被存储在window.event里. 在firefox中,或者其他浏览器,event事件会被相应的自定义函数获取.
代码如下:
document.onmousemove =move;
function move(evt)
{
evt=evt||window.event;
//evt.clientX,evt.clientY获取鼠标坐标
}

 二,捕捉鼠标点击。
       通过onmousedown,onmouseup捕获。
代码如下:
Layer.onmousedown=function()
 {
    document.onmousemove =move;
 }
 document.onmouseup=function()
 {
   document.onmousemove=null;
 };
     

3,移动元素。
      更改拖拽层的top和left的属性即可。但是为了保证拖拽层相对于鼠标的位置,要做点处理。
不再啰嗦,完整代码如下:
function dragged(title,body)
{
 var n_left,n_top;
 var div_body=document.getElementById(body);
 var div_title=document.getElementById(title);
 div_body.style.position="absolute";
 div_title.unselectable="on";
 div_title.style.cursor="move";
 div_body.unselectable="on";
 div_title.onmousedown=function()
 {
 this.style.cursor="default";
 document.onmousemove =move;
 }
 document.onmouseup=function()
 {
 document.onmousemove=null;
 n_left=null;n_top=null;
 div_title.style.cursor='move';
 };
 function move(evt)
 {
 evt=evt||window.event;
 if(!n_left) n_left=document.body.scrollLeft+evt.clientX-parseInt(div_body.style.left.replace("px",""));
 if(!n_top) n_top=document.body.scrollTop+evt.clientY-parseInt(div_body.style.top.replace("px",""));
 div_body.style.left=document.body.scrollLeft+evt.clientX-n_left+"px";
 div_body.style.top=document.body.scrollLeft+evt.clientY-n_top+"px";
 }
}; 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息