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

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.οnmοusedοwn=function()
 {
    document.onmousemove =move;
 }
 document.οnmοuseup=function()
 {
   document.οnmοusemοve=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.οnmοusedοwn=function()
 {
 this.style.cursor="default";
 document.onmousemove =move;
 }
 document.οnmοuseup=function()
 {
 document.οnmοusemοve=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";
 }
};
 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值