使用JavaScript无法正常显示mousex和mousey位置

时间:2014-03-12 04:22:31

标签: javascript

HTML和JavaScript代码如下所示,我在mozilla和chrome中检查过它并且它无效。

这是HTML部分

<form name ="show">
        <input type="text" name="mouseXField" >Mouse X Position<br />
        <input type="text" name="mouseYField" >Mouse Y Position<br />
    </form>

这是javascript部分

var mie = (navigator.appName == "Microsoft Internet Explorer") ? true : false;
    if (!mie) {

        document.captureEvent(Event.MOUSEMOVE);
        document.captureEvent(Event.MOUSEDOWN);
    }


    document.onmousemove = mousePos();
    document.onmousedown = mouseClicked();

    var mouseClick=0;
    var keyClicked=0;

    var mouseX = 0;
    var mouseY = 0;

    function mousePos (e) {

        if (!mie) {
            mouseX = e.pageX; 
            mouseY = e.pageY;
        }
        else {
            mouseX = event.clientX + document.body.scrollLeft;
            mouseY = event.clientY + document.body.scrollTop;
         }

    document.show.mouseXField.value = mouseX;
    document.show.mouseYField.value = mouseY;

    return true;
    }

2 个答案:

答案 0 :(得分:1)

以下是jquery的解决方案:fiddle

var IE = document.all?true:false
if (!IE) document.captureEvents(Event.MOUSEMOVE)
document.onmousemove = getMouseXY;
document.onmousemove = getMouseXY;
        var tempX = 0;
        var tempY = 0;
        function getMouseXY(e) {
            if (IE) { 

            tempX = event.clientX + document.body.scrollLeft
            tempY = event.clientY + document.body.scrollTop
            } 
            else 
            {  
             tempX = e.pageX
             tempY = e.pageY
            }  

            $('#spnCursor').html("x: " + tempX+" y: "+ tempY);

            return true
            }

答案 1 :(得分:0)

在您声明的else块中引用的事件变量在哪里?

你还可以发布html吗?

一个快速的谷歌透露了几个jsfiddle页面,实现了你的目标。