zoukankan      html  css  js  c++  java
  • 兼容IE FF 获取鼠标位置

    由于Firefox和IE等浏览器之间对js解释的方式不一样,firefox下面获取鼠标位置不能够直接使用clientX来获取。网上说的一般都是触发mousemove事件才行。我这里有两段代码,思路都一样,就是风格不同。


    第一段代码是利用全局变量来获取实时鼠标的位置。
    var xPos; var yPos;

    window.document.onmousemove(function(evt){
          evt=evt ||
    window.event;
         if(evt.pageX){
              xPos=evt.pageX;
             
    yPos=evt.pageY;
          } else {
             
    xPos=evt.clientX+document.body.scrollLeft-document.body.clientLeft;
             
    yPos=evt.clientY+document.body.scrollTop-document.body.clientTop;
         
    }
    });

    因为IE和Firefox对clientX的解析不一样,IE认为clientX是鼠标相对整个页面左上角的位置,而Firefox认为是相对当前所见页面左上角的位置。而这段代码最终返回的结果是整个页面左上角的位置。这段代码的缺陷是,xPos和yPos是实时变动的。


    第二段代码是通过函数获取当前时刻的鼠标坐标值
    function getPosition(event){
           event=
    event || window.event;
           if(event.pageX || event.pageY){
              
    return {x:event.pageX, y:event.pageY};
           }
           return
    {x:event.clientX + document.body.scrollLeft - document.body.clientLeft,
       
           y:event.clientY + document.body.scrollTop   -
    document.body.clientTop
          
    };
    }
    这段代码的来源是这里,这个网站还提供了一些简单的样例给我们玩耍。这个函数和刚才的函数理论是一致的,先触发mousemove事件,然后获取了事件之后,分别判断浏览器类型。这段代码的优点是,不适用全局变量,并且可以随用随拿,只要调用这个函数,就能够获取鼠标坐标。

  • 相关阅读:
    [Leetcode] Convert Sorted List to Binary Search Tree
    [Leetcode] Sqrt(x)
    [Leetcode] Pow(x, n)
    [Leetcode] Balanced Binary Tree
    [Leetcode] Convert Sorted Array to Binary Search Tree
    [Leetcode] Construct Binary Tree from Preorder and Inorder Traversal
    [Leetcode] Remove Element
    [Leetcode] Letter Combinations of a Phone Number
    [Leetcode] Generate Parentheses
    [Leetcode] Valid Parentheses
  • 原文地址:https://www.cnblogs.com/walle2014/p/3660009.html
Copyright © 2011-2022 走看看