2011-02-15 24 views
2

我在這裏要做的是在使用MooTools提交表單之後,顯示一個跟隨光標的加載框。不過,我已將問題簡化爲1格1格。MooTools - 如何在提交表單時獲取鼠標位置?

腳本:

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)。在表單提交後有沒有辦法獲得鼠標位置?或者有另一種方法可以做到嗎?

任何建議,非常感謝!

更新時間:

我不想在提交表單前添加鼠標事件(鼠標移動)。原因很簡單,因爲我不希望JavaScript在不需要時繼續檢查鼠標位置。試着避免性能問題!

回答

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/>")); 
    }); 
})(); 

閱讀框位置後提交將返回光標:)

缺點:改變CSS的invis禁區前提交的延遲。

編輯更好的版本W/O的變化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/

+0

Dimitar,謝謝你的評論。我忘了提及一點,但你已經在「下行」中提到了它。這正是我爲什麼不想在開始時添加鼠標事件的原因。即使沒有必要,javascript仍會檢查鼠標移動的位置。 – Davuth 2011-02-16 01:11:36