如何在 JavaScript 中的元素上触发 Onmouseover 事件

how to trigger an onmouseover event on element in javascript?

本文关键字:Onmouseover 事件 元素 JavaScript      更新时间:2023-09-26

如标题所示,如何在 javascript 中的元素上触发 onmouseover 事件?请参考代码片段。我可以单击小黑框并执行onmouseover事件,而不是将鼠标悬停在大框上吗?目标不是将盒子变成蓝色,而是触发onmouseover事件。而且我需要只用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>

这应该有效:

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>

它应该是onmouseover()而不是mouseover()

document.getElementById('xyz').onmouseover();