为HTML元素实现鼠标悬停背景颜色更改的最简单方法是什么

What is the simplest way to implement mouseover background color change for HTML elements?

本文关键字:最简单 是什么 方法 颜色 背景 元素 HTML 实现 鼠标 悬停      更新时间:2023-09-26

I有以下样式:

a.button {
    background-color: orange;
    margin: .2cm;
    padding: .2cm;
    color: black;
    font-family: sans-serif;
    text-decoration: none;
    font-weight: bold;
    border: solid #000000;
}
a.buttonMouseover {
    background-color: darkGoldenRod;
    margin: .2cm;
    padding: .2cm;
    color: black;
    font-family: sans-serif;
    text-decoration: none;
    font-weight: bold;
    border: solid #000000;
}

以及以下javascript代码(我的第一个btw):

function backgroundChangeIn(element){
    if (element.className = "a.button"){element.className = "buttonMouseover";}
}
function backgroundChangeOut(element){
    if (element.className = "a.buttonMouseover"){element.className = "button";}
}

并且,下面的元素应该改变鼠标悬停时的背景:

<a class="button" href="" onmouseover="backgroundChangeIn(this)" onmouseout="backgroundChangeOut(this)">A Button</a>

到目前为止,它对我有效。但我想知道是否还有更好的方法。

(对所有代码感到抱歉)

根据您的目标浏览器,您可以使用hover伪标记。

a.button {
    background-color: orange;
    margin: .2cm;
    padding: .2cm;
    color: black;
    font-family: sans-serif;
    text-decoration: none;
    font-weight: bold;
    border: solid #000000;
}
a.button:hover {
    background-color: darkGoldenRod;
}

以下是w3schools的一些文档。看起来它在所有远程现代浏览器上都得到了很好的支持。

请注意,普通样式规则和悬停样式规则都适用,悬停优先。因此,您只需要在悬停规则中放入更改内容即可。

sblundy拥有基本权利。除此之外,所有现代浏览器都允许您在<a>然而IE6不会在任何其他元素上识别这一点。

在IE6中,当您悬停时,您需要某种JavaScript来添加类名。我喜欢使用jQuery,这样做的方式如下:

$(function(){
  $('.hoverable').hover(function(){
    $(this).addClass('hover');
  },
  function(){
    $(this).removeClass('hover');
  })
})

当悬停在类"hoverable"的所有元素上时,它们将被赋予一个悬停类。

a.button, a.button:hover {
    margin: .2cm;
    padding: .2cm;
    color: black;
    font-family: sans-serif;
    text-decoration: none;
    font-weight: bold;
    border: solid #000000;
}
a.button {
    background-color: orange;
}
a.button:hover {
    background-color: darkGoldenRod;
}

和:

<a class="button" href="">A Button</a>

您可以使用像jQuery这样的库来简化操作。