2

我在这里要做的是在使用 MooTools 提交表单后显示一个跟随光标的加载框。但是,我已将问题简化为 1 个 div 和 1 个表单。

脚本:

document.addEvent('domready', function(){

    $('test_form').addEvent('submit', function(){
        var box = $('box');

        document.addEvent('mousemove', function(e){
            box.setStyles({
                top: e.page.y,
                left: e.page.x
            });
        });


        box.setStyle('display', 'block');

        return false;
    });
});

html:

<div id="box">
</div>

<form id="test_form" action="">
    <label>Name: </label><input type="text" name="name" /><br/>
    <input type="submit" value="Submit" />
</form>

CSS:

#box {
    width: 50px;
    height: 50px;
    background-color: blue;
    position: absolute;
    display: none;
}

#test_form {
    margin-left: 150px;
}

当表单提交时,它会显示隐藏的蓝色 div 并跟随光标。但是,提交表单时,我无法使 div 出现在鼠标位置。在我们移动鼠标之前,'mousemove' 不会触发;因此,蓝色 div 在显示后立即出现在位置 (0,0)。有没有办法在提交表单后立即获取鼠标位置?还是有其他方法可以做到这一点?

非常感谢任何建议!

更新:

我不想在提交表单之前添加鼠标事件(mousemove)。原因很简单,因为我不希望 javascript 在不需要时继续检查鼠标位置。尽量避免性能问题!

4

1 回答 1

1

基本上,提交是一个事件,但它的 event.type 是提交,它不会包含鼠标信息。

您的赌注是重新排列您的 javascript,以便它一直安静地移动框,并在提交时通过更改显示来显示框。类似的东西:

http://jsfiddle.net/jtLwj/

(function() {
    var box = $('box');

    document.addEvent('mousemove', function(e) {
        box.setStyles({
            top: e.page.y,
            left: e.page.x
        });
    });

    $('test_form').addEvent('submit', function(ev) {
        ev.stop();
        box.setStyle('display', 'block');
        var sizes = box.getPosition();
        box.set("html", [sizes.x, ' x ', sizes.y].join("<br/>"));
    });
})();

提交后阅读框位置将返回您的光标:)

缺点:在提交之前更改 invis 框的 css 的延迟。

始终编​​辑更好的版本,而无需更改 dom:

(function() {
    var lastEventObject, eventListener = function(e) {
        // keep a scoped referene of the last known mouse event object
        lastEventObject = e;
    };

    document.addEvent('mousemove', eventListener);

    document.id('test_form').addEvent('submit', function(e) {
        e.stop();
        // not needed anymore...
        document.removeEvent("mousemove", eventListener);

        // show the box at last known mouse loc
        document.id("box").setStyles({
            display: 'block',
            left: lastEventObject.page.x,
            top: lastEventObject.page.y
        });

        // attach to mousemove or whatever....

    });
})();

恐怕这是最好的了。对事件对象的引用的足迹充其量是最小的。

小提琴:http: //jsfiddle.net/dimitar/jtLwj/1/

于 2011-02-15T14:26:25.030 回答