javascript - 如何使用带有 svg 的 javascript onmouseover 函数来获取类名?
问题描述
我有一个 SVG 地图,当鼠标悬停在地图的某个区域时,我想在其中更改侧面板上的文本。我想将文本更改为包含鼠标悬停区域的锚的类名。目前,每当我将鼠标悬停在地图上时,它都会在侧面板中返回未定义。
我尝试将代码设置为仅在类名不等于 nil 时才起作用,并且该函数没有触发,所以我一定不会在鼠标悬停时获得锚标记。
HTML(删除了不相关的代码)
<p onmouseover="houseQuickOverview()">
<svg ... >
<g id="G_Areas" ... >
<a class="HD-002" ... >
<path gg:cat="2" d="M ... />
</a>
<a class="HD-003" ... >
<path gg:cat="2" d="M ... />
</a>
JavaScript
let houseQuickOverview = function () {
let district = this.className;
document.querySelector(".districtNumber").innerHTML = district;
}
当我将鼠标悬停在包含 SVG 的段落上时,当鼠标触摸其中一个锚点时,我希望它将锚点的类名返回到 DistrictNumber div。它目前只返回未定义的 div。
解决方案
试试下面的,在你的具体情况下,你可能需要像这样缩小 els
const anchor = document.querySelectorAll("p a"); // to select only <a> under <p>
(function() {
const anchor = document.querySelectorAll("a")
for (const a of anchor) {
a.addEventListener('mouseover', function(event) {
document.getElementById('result').innerHTML = event.currentTarget.className;
})
}
})();
#result {
color: red;
}
a {
display: block;
margin: 1em;
}
<a class="HD-002">
123
</a>
<a class="HD-0022">
456
</a>
<a class="HD-0023">
789
</a>
<a class="HD-0024">
101112
</a>
<div id="result"></div>
推荐阅读
- javascript - 在没有 Node.js 的情况下导出 JavaScript 对象
- dompdf - 如何在新页面(自动生成)或使用 Twig 使用 dompdf 强制分页后插入内容?
- javascript - 为什么 Object 从整数数组中删除重复元素
- c# - 如何在 C# 中将 System.Windows.Forms.DataVisualization.Chart 图表导出到 Word
- go - 为什么 net/rpc/client 的 Go 方法需要缓冲通道?
- python - 将列表列表中的特定项目从字符串转换为双精度?
- list - Powershell:对于每个带有列表问题的循环
- oracle - 在 Oracle (PL/SQL Developer) 中声明变量
- swift - 如何在使用 CABasicAnimation 时重复相同的动画
- python - 如何确定令牌是否是 Spacy 中实体的一部分?