2017-09-23 33 views
0

我正試圖在子div上調用onmouseout事件。爲父div元素調用javascript事件一次

雖然函數outofdiv一旦光標離開父div,就會被調用。

函數被再次調用當不同子格之間光標旅行,我不希望發生

請建議使用JavaScript的

<div id="maze" onmouseout="outofdiv();"> 

      <div id="start" onClick="start();">S</div> 
      <div class="boundary"></div> 
      <div class="boundary"></div> 
      <div class="boundary"></div> 
      <div class="boundary"></div> 
      <div class="boundary"></div> 
      <div id="end" onClick="end();">E</div> 
</div> 


function outofdiv(){ 
alert("something") 
+0

'outofdiv()'做了什麼?你能否詳細說明問題 –

+0

@GthathamShiva這不是關於功能; OP剛剛誤解了'onmouseout'的用法。根據W3Schools的說法:_「鼠標指針移出某個元素或移出某個子元素時,發生鼠標移動事件。」_ –

+0

請提出任何提示當鼠標指針移出父元素時不提示的方法,而不是在移動時子元素之間 –

回答

0

你可以找到任何方法回答這裏:Prevent onmouseout when hovering child element of the parent absolute div WITHOUT jQuery

但總結起來,你必須使用另一個功能:

function onMouseOut(event) { 
    //this is the original element the event handler was assigned to 
    var e = event.toElement || event.relatedTarget; 
    if (e.parentNode == this || e == this) { 
    return; 
    } 
    alert('MouseOut'); 
    // handle mouse event here! 
} 

document.getElementById('maze').addEventListener('mouseout',onMouseOut,true); 

從上面鏈接中的第一個答案中獲取並修改的代碼。

0

不知道,但它可能對你有所幫助

var i = 0; 
 
$("div.overout") 
 
    .mouseover(function() { 
 
    i += 1; 
 
    $(this).find("span").text("mouse over x " + i); 
 
    }) 
 
    .mouseout(function() { 
 
    $(this).find("span").text("mouse out "); 
 
    }); 
 
    
 
var n = 0; 
 
$("div.enterleave") 
 
    .mouseenter(function() { 
 
    n += 1; 
 
    $(this).find("span").text("mouse enter x " + n); 
 
    }) 
 
    .mouseleave(function() { 
 
    $(this).find("span").text("mouse leave"); 
 
    });
div.out { 
 
    width: 40%; 
 
    height: 120px; 
 
    margin: 0 15px; 
 
    background-color: #d6edfc; 
 
    float: left; 
 
    } 
 
    div.in { 
 
    width: 60%; 
 
    height: 60%; 
 
    background-color: #fc0; 
 
    margin: 10px auto; 
 
    } 
 
    p { 
 
    line-height: 1em; 
 
    margin: 0; 
 
    padding: 0; 
 
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> 
 

 

 
    
 
<div class="out overout"> 
 
    <span>move your mouse</span> 
 
    <div class="in"> 
 
    </div> 
 
</div> 
 
    
 
<div class="out enterleave"> 
 
    <span>move your mouse</span> 
 
    <div class="in"> 
 
    </div> 
 
</div>

您也可以參考這個鏈接https://api.jquery.com/mouseover/

+0

1)你沒有在你的例子中包含jQuery,所以它什麼都不做; 2)OP明確指出:_「請僅提供任何使用** javascript **的方法」_ –

0

只需使用下面的JavaScript:

var i = 0; 
function outofdiv() { 
    if (!i++) { 
    alert("something"); 
    } 
} 

這會打電話只有一次單頁加載。

0

這被稱爲事件冒泡。 onmouseout事件由子元素div觸發,並通過其DOM層次結構進行冒泡,在此情況下,該子元素髮送給父代divonmouseout事件處理程序。

您可以使用event.targetevent.currentTarget來確定事件是否已冒泡。

if (event.target!=event.currentTarget) return; 

爲您outofdiv功能的第一道防線。如果父div不是onmouseout事件的發起者,則可以防止該功能繼續。

相關問題