【问题标题】:Getting the cursor position using javascript not working in firefox使用javascript获取光标位置在firefox中不起作用
【发布时间】:2010-07-14 07:41:00
【问题描述】:

我有一个类似的javascript

function getCursorPosition(e) {
        e = e || window.event;
        var cursor = {x:0, y:0};
        if (e.pageX || e.pageY) {
            cursor.x = e.pageX;
            cursor.y = e.pageY;
        } 
        else {
            cursor.x = e.clientX + 
                (document.documentElement.scrollLeft || 
                document.body.scrollLeft) - 
                document.documentElement.clientLeft;
            cursor.y = e.clientY + 
                (document.documentElement.scrollTop || 
                document.body.scrollTop) - 
                document.documentElement.clientTop;
        }
        return cursor;
    }

document.onmouseup = function(e){
    cursor = getCursorPosition();
    alert(cursor.x + ':' + cursor.y);
};

此代码提醒单击光标的 X 和 Y 位置。这在 IE 7/8、Chrome/Safari、Opera 10 中运行良好。但在使用 firefox 4.0 beta 1 进行测试时,它无法正常工作。

在谷歌上搜索时,许多网站都给了我相同的代码。但它不适用于 ff 4.0b

这是 ff 4.0b 的错误吗?或者任何人都可以建议我另一个跨浏览器光标位置脚本吗?

【问题讨论】:

标签: javascript firefox cursor


【解决方案1】:

您应该将事件传递给 getCursorPosition 方法:

document.onmouseup = function(e){
    cursor = getCursorPosition(e); //<== added the "e" argument here
    alert(cursor.x + ':' + cursor.y);
};

【讨论】:

    【解决方案2】:

    或者完全丢掉getCursorPosition()而使用极其跨浏览器的jQuery:

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
    
    <script type="text/javascript">
        function jQueryMain ()
        {
            $(document).mouseup (function (evt) {alert (evt.pageX + ':' + evt.pageY);} );
        }
    
        $(document).ready (jQueryMain);
    </script>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-16
      • 2013-08-28
      • 2023-01-31
      • 2016-03-02
      • 2015-02-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多