首页 > 解决方案 > 创建事件 - 激发姓氏

问题描述

我在 w3school 上找到了一个带有 createevent 的刺激 '*',现在我正在尝试创建一个姓氏“Markous Max”。Markous 是我的名字,Max 是我的姓氏。这可以在同一行完成吗?

<!DOCTYPE html>
<html>
<body>
<style>
div {
  padding:50px;
  background-color: black;
  color: white;
}
</style>
<script>
function myFunction(event) {
var x = document.createEvent("MouseEvent");
x.initMouseEvent("mouseover", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);

document.getElementById("myDiv").dispatchEvent(x);
}
</script>



<div onmouseover="this.innerHTML += 'M';" id="myDiv"></div>
<div onmouseover="this.innerHTML += 'a';" id="myDiv"></div>
<div onmouseover="this.innerHTML += 'r';" id="myDiv"></div>
<div onmouseover="this.innerHTML += 'k';" id="myDiv"></div>
<div onmouseover="this.innerHTML += 'o';" id="myDiv"></div>
<div onmouseover="this.innerHTML += 'u';" id="myDiv"></div>
<div onmouseover="this.innerHTML += 's';" id="myDiv"></div>
<div onmouseover="this.innerHTML += '';" id="myDiv"></div>

模拟鼠标悬停

标签: javascript

解决方案


myDiv对多个 div 使用相同的 id。id 只能与一个元素一起使用。因此,将每个 div 替换为idclass

在 JS 中,通过 获取元素className,循环遍历每个元素,然后调度事件。

有关更多详细信息,请参阅以下代码段 -

function myFunction(event) {
  var x = document.createEvent("MouseEvent");
  x.initMouseEvent("mouseover", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);

  //Get elements by className - 
  var elements = document.getElementsByClassName("myDiv");
  
  //loop through each of the element
  for(let i = 0; i<elements.length; i++){
    //dispatch the event for each of the elements
    elements[i].dispatchEvent(x);
  }
}

//Firing the function here. This will call the function only one time. You can create a button and call this function onclick.
myFunction(event);
body{
  display: flex;
}

div {
  padding:50px;
  background-color: black;
  color: white;
}
<!--Replace id with class-->

<div onmouseover="this.innerHTML += 'M';" class="myDiv"></div>
<div onmouseover="this.innerHTML += 'a';" class="myDiv"></div>
<div onmouseover="this.innerHTML += 'r';" class="myDiv"></div>
<div onmouseover="this.innerHTML += 'k';" class="myDiv"></div>
<div onmouseover="this.innerHTML += 'o';" class="myDiv"></div>
<div onmouseover="this.innerHTML += 'u';" class="myDiv"></div>
<div onmouseover="this.innerHTML += 's';" class="myDiv"></div>
<div onmouseover="this.innerHTML += '';" class="myDiv"></div>


推荐阅读