【问题标题】:Create highlight effect on hover an element在悬停元素时创建突出显示效果
【发布时间】:2021-03-22 17:43:28
【问题描述】:
当我将鼠标悬停在每个 div 元素上时,我尝试在每个 <a> 元素上制作高亮效果,但它不起作用并且控制台显示此错误
“未捕获的类型错误:无法设置未定义的属性‘背景’
在 highlight_function"
enter image description here
function highlight_function () {document.getElementsByTagName("a").style.background="#80ff00"};
document.getElementsByTagName("div").addEventListener("mouseover",highlight_function())
【问题讨论】:
标签:
javascript
html
css
web
【解决方案1】:
我认为这是因为document.getElementsByTagName("a") 是一个数组,而您试图在数组而不是每个元素中设置样式。
您应该创建一个 for 循环来更改每个元素的背景样式,或者添加一个样式标签,例如 a {background: "#80ff00"}。
但是你不能像这样为数组定义样式
【解决方案2】:
index.html
<html lang="en">
<head>
</head>
<body>
<div>
<a href="#"> something</a>
</div>
</body>
<script>
function highlight_function() {
const a = document.querySelector('a');
a.style.background = "#80ff00"
}
const div = document.querySelector('div');
div.addEventListener('mouseover', highlight_function);
</script>
</html>
【解决方案3】:
您可以通过添加 CSS 来简单地添加高亮效果或更改背景颜色,如下所示:
<!DOCTYPE html>
<html>
<head>
<style>
p:hover {
background-color: green;
}
</style>
</head>
<body>
<p id="hometown">I live in Pakistan</p>
</body>
</html>
【解决方案4】:
我认为背景属性不适用于<a> 标记。尝试在您的函数中执行此操作:
document.getElementsByTagName("a").style.color="#80ff00"
【解决方案5】:
你可以试试这个
function highlight_function() {
document.getElementById("a").style.backgroundColor = "#80ff00";
};
<div id="div">
<a id="a" onmouseover="highlight_function()">Hell</a>
</div>
【解决方案6】:
当您拨打电话时
document.getElementsByTagName("a")
它将返回给您的 html 元素集合,因此没有样式属性
你可以通过它使用for循环
for(var a of document.getElementsByTagName("a")) {
a.style.background="#80ff00";
}