2015-03-13 75 views
1

正如標題所示,如何在JavaScript中的元素上觸發一個onmouseover事件?請參閱代碼片段。我可以點擊小黑盒並執行onmouseover事件,而不是懸停在大盒子上嗎?目標不是將箱子變成藍色,而是觸發onmouseover事件。而且我還需要用JavaScript來完成,不需要Jquery。如何在javascript中的元素上觸發onmouseover事件?

function showBlue() { 
 
\t document.getElementById('xyz').style.background = "#425dff"; 
 
} 
 
function showRed() { 
 
\t document.getElementById('xyz').style.background = "#e2e2e2"; 
 
}
#abc{width: 50px; height: 50px; background: #000000; color:#ffffff; cursor: pointer;} 
 
#xyz{width: 200px; height: 200px; background: #e2e2e2;}
<div id="abc"><a>click me</a></div> 
 

 
</br> 
 

 
<div id="xyz" onmouseover="showBlue()" onmouseout="showGrey()"></div>

我試過,但我:(沒有工作

<script> 
    document.getElementById('abc').addEventListener("click", triggerFunction); 

    function triggerFunction() { 
     document.getElementById('xyz').mouseover(); 
    } 
</script> 
+0

我需要它,如果可能的 – 2015-03-13 18:56:11

+0

純JavaScript的解決方案,我希望我能downvote對此有何評論Teemu :( – 2015-03-13 18:56:26

回答

2

這應該工作:

function showBlue() { 
 
\t document.getElementById('xyz').style.background = "#425dff"; 
 
} 
 
function showGrey() { 
 
\t document.getElementById('xyz').style.background = "#e2e2e2"; 
 
} 
 
function triggerMouseOver() { 
 
    document.getElementById('xyz').onmouseover(); 
 
}
#abc{width: 50px; height: 50px; background: #000000; color:#ffffff; cursor: pointer;} 
 
#xyz{width: 200px; height: 200px; background: #e2e2e2;}
<div id="abc" onclick="triggerMouseOver()"><a>click me</a></div> 
 

 
</br> 
 

 
<div id="xyz" onmouseover="showBlue()" onmouseout="showGrey()"></div>

你也可以簡單地這樣做:

<div id="abc" onclick="document.getElementById('xyz').onmouseover()"><a>click me</a></div> 
+0

你元素使用'showGrey',但你只聲明'showBlue'和'showRed'。我認爲'showRed'功能需要重新命名? – ssube 2015-03-13 19:05:47

+0

這隻適用於內嵌處理程序... – Teemu 2015-03-13 19:06:21

+0

是的,他的代碼有錯誤的名稱,但我忘了修復它。我會更新我的答案代碼。 – Gremash 2015-03-13 19:06:44

1

應該是onmouseover()代替mouseover()

document.getElementById('xyz').onmouseover(); 
相關問題