[英]Remove mouseover in div with JS-Function
我希望能夠啟用和禁用某個div-id的mouseover函數調用,但這將無法正常工作。
function revertcontent(){
document.getElementById('content').src='img/content.jpg';
document.getElementById('zentrum').addEventlistener("mouseover",true);
}
function dias( klick ){
document.getElementById('content').src='img/'+klick+'.jpg';
document.getElementById('zentrum').removeEventlistener("mouseover",true);
}
這是div,具有mouseover函數調用:
<div class="cont">
<div id="zentrum" onmouseover="showvita()" onmouseout="revertcontent()">
<img src="img/content.jpg" id="content" />
</div>
</div>
因此,我基本上想在調用函數(dias)時禁用鼠標懸停,並在調用函數(revertcontent)時重新啟用鼠標懸停。 (revertcontent確實也會被其他按鈕按下來調用。
它與EventListeners似乎根本不起作用。
在此先感謝您的幫助! 我不是編碼員,而是業余愛好者
為什么不使用jQuery
,它使它變得更容易。 使您的html
看起來像這樣
<div class="cont"><div id="zentrum">
<img src="img/content.jpg" id="content" />
</div></div>
然后像這樣使用jQuery
hover()
函數
$('div#zentrum').hover(function(){
$('img#content').attr('src', 'img/content.jpg');
},
function(){
// run all your code for the mouseleave here
});
只是沒有足夠的空間來輕松評論。
我將代碼更改如下:
function showvita(){ document.getElementById('content').src='img/vita.jpg'; document.getElementById('zentrum').onmouseout = "revertcontent()"; } function revertcontent(){ document.getElementById('content').src='img/content.jpg'; document.getElementById('zentrum').onmouseover = "showvita()"; } function dias( klick ){ document.getElementById('content').src='img/'+klick+'.jpg'; document.getElementById('zentrum').onmouseover = 'null'; document.getElementById('zentrum').onmouseout = 'null'; }
<div class="cont" > <div id="zentrum" onmouseover="showvita()" onmouseout="revertcontent()"> <img src="img/content.jpg" id="content" /> </div> </div>
現在,將鼠標移出div后,我陷入了vita.jpg的困境。 在函數dias被調用並隨后再次還原內容之后,我陷入了content.jpg的困境,而沒有更多的鼠標懸停功能。 那么這里發生了什么? 是否.onmouseover="showvita()";
調用該函數,還是在div中為mouseover選項設置該值? 我認為我真的只需要重置值即可。
通常,嘗試更改鼠標懸停屬性是一種不好的做法。 一種更簡單的方法是設置一個變量,例如“ isMouseoverEnabled”,然后在鼠標懸停處理程序中,如果該變量為false,則立即返回。 另外,我看到您的代碼每次在鼠標revertContent
過它時都會調用revertContent
,這會添加大量重復的事件偵聽器。
另外,如果您使用JavaScript而不是mouseover屬性來綁定事件,那么稍后取消綁定是很簡單的。 例如,您的代碼可能如下所示:
$(document).ready(function() {
var onMouseOver = function(){
// Do stuff here
};
var revertcontent = function() {
$('#content')[0].src ='img/content.jpg';
// We're calling "off" just in case "dias" hasn't been called,
// to avoid double event binding
$('#zentrum').off('mouseover', onMouseOver )
.on('mouseover', onMouseOver );
};
var dias = function(klick) {
$('#content')[0].src ='img/content.jpg';
$('#zentrum').off('mouseover', onMouseOver );
};
revertcontent();
});
附帶一提,jquery確實更適合諸如此類的東西,因為它可以在所有瀏覽器中實現標准化。 它使您可以花費更多的時間編寫代碼,而花費更少的時間來找出鼠標事件中的細微差別。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.