首页 > 解决方案 > 如何使用带有 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。

标签: javascripthtmlsvgclassname

解决方案


试试下面的,在你的具体情况下,你可能需要像这样缩小 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>


推荐阅读