如标题所示,如何在javascript中触发元素上的onmouseover
事件?请参阅Code Snippet。我可以点击小黑框并执行onmouseover
事件,而不是悬停在大盒子上吗?目标不是将框变为蓝色,而是将onmouseover
事件触发TRIGGER。而且我需要这只用JavaScript来完成,请不要Jquery。
function showBlue() {
document.getElementById('xyz').style.background = "#425dff";
}
function showRed() {
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 :(得分:3)
这应该有效:
function showBlue() {
document.getElementById('xyz').style.background = "#425dff";
}
function showGrey() {
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>
答案 1 :(得分:1)
应该是onmouseover()
而不是mouseover()
document.getElementById('xyz').onmouseover();