简体   繁体   English

在 hover 一个元素上创建高亮效果

[英]Create highlight effect on hover an element

I tried to make highlight effect on each <a> element while I hover on each div element but it doesn't work and console shows this error我尝试对每个<a>元素进行突出显示效果,而我在每个div元素上使用 hover 但它不起作用并且控制台显示此错误

"Uncaught TypeError: Cannot set property 'background' of undefined at highlight_function" “未捕获的类型错误:无法在 highlight_function 处设置未定义的属性‘背景’”

enter image description here在此处输入图像描述

function highlight_function () {document.getElementsByTagName("a").style.background="#80ff00"};

             document.getElementsByTagName("div").addEventListener("mouseover",highlight_function())

you can simply add highlight effect or change the background color by adding the CSS as follows:您可以通过添加 CSS 来简单地添加高亮效果或更改背景颜色,如下所示:

 <:DOCTYPE html> <html> <head> <style> p:hover { background-color; green; } </style> </head> <body> <p id="hometown">I live in Pakistan</p> </body> </html>

I think it's because document.getElementsByTagName("a") is an array, and you are trying to set style on the array and not in each element.我认为这是因为document.getElementsByTagName("a")是一个数组,并且您试图在数组而不是每个元素中设置样式。

You should either make a for loop to change background style of each element or add a style tag like a {background: "#80ff00"} .您应该创建一个 for 循环来更改每个元素的背景样式,或者添加一个样式标签,如a {background: "#80ff00"}

But you can't define style to an array like this但是你不能像这样为数组定义样式

index.html索引.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>

I don't think background property will work on an <a> tag.我认为背景属性不适用于<a>标记。 Try doing this in your function:尝试在您的 function 中执行此操作:

document.getElementsByTagName("a").style.color="#80ff00"

Here is you can try this这是你可以试试这个

 function highlight_function() { document.getElementById("a").style.backgroundColor = "#80ff00"; };
 <div id="div"> <a id="a" onmouseover="highlight_function()">Hell</a> </div>

when you make this call document.getElementsByTagName("a") it will return to you collection of html elements so there is no style property you can use for loop through it当您进行此调用时document.getElementsByTagName("a")它将返回给您 html 元素的集合,因此没有样式属性可以用于循环它

for(var a of document.getElementsByTagName("a")) {
  a.style.background="#80ff00";
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM