2012-05-18 26 views
2

O.K.也許我問過類似的東西,但這是我的另一個問題。我將通過展示的代碼開始:關於鼠標事件的JavaScript DOM父/子關係

var MyClass = { 
    // Set up the events for the parent 
    // MyParent is a DIV 
    SetEvents: function() { 
     MyParent.onmouseover = function() { MyClass.MouseHover(MyParent); }; 
     MyParent.onmouseout = function() { MyClass.MouseOut(MyParent); }; 
    }, 

    // Function activated when moving the mouse over the parent 
    MouseHover: function(Parent) { 
     if (Parent) { 
     // Here I create the child, when moving the mouse over the parent control 
     // The child is an IMG 
      var child = document.createElement("img"); 
       child.id = "child"; 
       child.src = "child.png"; 
       child.style.float = "right"; 
      Parent.appendChild(child); 
     } 
    }, 

    // Function activated when moving the mouse out of the parent control 
    MouseOut: function(Parent) { 
     if (Parent) { 
      var child = document.getElementById("child"); 
      if (child) { 
       // On mouse out I remove the child 
       Parent.removeChild(child); 
      } 
     } 
    } 
} 

所以,這只是當我將鼠標移動到一個div出現一個簡單的圖像,然後當我將鼠標移出消失。然而,這並不是我想要的。

問題是,當鼠標位於父div上時,如果將其移動到子代img(仍在父代上方),則會觸發MouseOut()函數。

我一直在尋找解決方案和技巧,但這一切都是徒勞的。現在,我希望有人能夠發現問題。必須有一些我錯過了的JavaScript章節。感謝大家!

我加了一些圖片,來解釋這更好

Case 1 Case 2 Case 3 Case 4

最新通報 看起來像發生這種情況只有在IMG孩子dinamically創建。如果我之前創建它,只需更改它的src,它就可以工作。

JSSFIDLE DEMO 您可以在http://jsfiddle.net/E9q6e/1/

+0

謝謝你,F. Calderan – ali

+0

你可能使用[JS Fiddle](http://jsfiddle.net/)或類似的方法包含一個現場演示,向我們展示你在使用什麼? –

+0

+1圖像說明.. – Pranav

回答

0

看到這個劇本的工作(當然,不工作,更好地說)你可以嘗試檢查,如果Parent包含childMouseOut()

var ref=event.toElement || event.relatedTarget; // This line is pseudocode 
if(!Parent.contains(ref)){ 
    Parent.removeChild(child); 
} 
+0

如果您在http://jsfiddle.net/E9q6e/1/(我的腳本)上嘗試此操作,MouseOut將會被完全禁用 – ali

+0

在IE中它的工作原理(取決於你如何分配事件處理程序)。對於其他瀏覽器,您需要獲取對Event對象的引用。注意這句話:「這一行是僞代碼」。 – Teemu