javascript - 创建事件 - 激发姓氏
问题描述
我在 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>
模拟鼠标悬停
解决方案
您myDiv
对多个 div 使用相同的 id。id 只能与一个元素一起使用。因此,将每个 div 替换为id
。class
在 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>
推荐阅读
- php - 使用 woocommerce 预订动态询问人名。?
- android - 在另一个 ndkbuild 库上制作 CMake 本机库
- python - 在Python中将数据框从水平重塑为垂直
- javascript - 为什么输入字段中的相同字符串和JS中变量字符串的静态值的字符串长度不同
- php - 通过 phpseclib 使用“$_SERVER text”编写 php 文件:SSH2
- image - 多张图片的平均图片
- c# - 调用带有可变参数的函数时出现 System.Windows.Markup.XamlParseException
- c# - 如何在c#中使用xdocument替换xml的元素
- monitoring - 增加 Prometheus 存储保留
- laravel - 使用宅基地作为服务器使用laravel进行电子邮件登录