仅在鼠标悬停时"href"参数



我有以下问题。我在链接上有预定义的href,无法在html中更改或删除。我需要这个href只有onmouseover。所以我删除了它:

document.getElementsByClassName("class")[0].removeAttribute("href");

现在我需要添加这个href,但只有onmouseover,所以默认情况下没有href属性,onmouseover会启用它。但这个和类似的解决方案不起作用:

document.getElementsByClassName("class")[0].onmouseover="this.href = 'urlHere';"

有办法做到这一点吗?

正如我在评论中提到的,你几乎肯定不应该这样做,因为这会破坏可访问性。如果您只是想更改一些样式,请使用CSS和:hover伪类选择器。

然而,如果你真的有一个合法的用例,最好的方法是使用WeakMap:

const links = document.querySelectorAll('.link-class-name')
const map = new WeakMap()
links.forEach(link => {
map.set(link, link.href)
link.removeAttribute('href')
link.addEventListener('mouseenter', () => link.href = map.get(link))
link.addEventListener('mouseleave', () => link.removeAttribute('href'))
})

WeakMap很酷,因为它们允许您以一种在不再需要时可以垃圾收集的方式存储关于任意对象的任意元数据。这使得它们非常适合存储和检索DOM节点的数据。

如果您将鼠标悬停在<a>标记上,请将事件侦听器附加到文档对象,然后添加链接;否则,如果您将光标悬停在它之外,请删除href属性。

示例:

const link = document.getElementsByClassName("class")[0];
link.removeAttribute("href");
document.addEventListener('mouseover', (e) => {
if (e.target.tagName === 'A') {
link.setAttribute('href', 'http://www.google.com');
} else {
link.removeAttribute('href');
}
})
<a class="class" href="http://www.google.com">Google site</a>

最新更新