0

我想在 onmousemove 事件上使用 javascript 更改左侧和顶部样式元素,但它不起作用。

我的 onmousemove 事件代码:

function mymove(e)
{
var event=new MouseEvent(e);
    x = 20;
    y = 10;     

    document.getElementById('mye').style.left = event.pageX + x+'px' ;
    document.getElementById('mye').style.top = event.pageY - y+'px';


    }
4

1 回答 1

3

Guessing on the markup and CSS. Also, I think the e properties might change per browser. This works in Firefox (9).

CSS

#mye {
    height: 25px;
    width: 250px;
    position: absolute;
    background: #ddd;
}

Markup

<div id="mye">Content</div>

Javascript

var mymove = function (e) {
    var x = 20,
        y = 10,
        mye = document.getElementById('mye');

    mye.style.left = (parseInt(e.clientX) + x) + 'px';
    mye.style.top = (parseInt(e.clientY) - y) + 'px';
};

// Don't forget to add this in an onload or ondomready.
document.getElementById('mye').onmousemove = mymove;

http://jsfiddle.net/3YdEa/6/

And note, as Jeffrey Sweeney mentions, attaching to the window.onmousemove is probably more common:

window.onmousemove = mymove;

http://jsfiddle.net/3YdEa/7/

Here is Quirksmode on the mouse event position property situation. This is a few years old, however.

Here's another StackOverflow question, and of course jQuery's $.mousemove(), which will eliminate the differences between browsers.

于 2012-02-04T14:25:49.623 回答