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

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

提问人:jjnguy 提问时间:11/4/2008 最后编辑:Blair Conradjjnguy 更新时间:12/9/2008 访问量:4018

问:

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 代码(顺便说一句,我的第一个):

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>

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

(对不起,所有代码)

JavaScript HTML

评论


答:

10赞 sblundy 11/4/2008 #1

根据您的目标浏览器,您可以使用伪标记。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的文档。看起来它在所有远程现代浏览器上都得到了很好的支持。

请注意,将同时应用普通和悬停样式规则,悬停优先。因此,您只需要在悬停规则中输入哪些更改即可。

1赞 Sören Kuklau 11/4/2008 #2
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>
-1赞 Davide Gualano 11/4/2008 #3

您可以使用像 jQuery 这样的库来简化事情。

评论

0赞 Christopher Tokar 11/6/2008
也许吧,但对于像使用悬停伪标签这样简单的解决方案,当您可以使用简单的锤子时,就没有必要使用大锤。
5赞 philnash 11/4/2008 #4

SBLUNDY拥有正确的基础知识。除此之外,所有现代浏览器都允许您在 <a> 上使用悬停伪元素,但 IE6 不会在任何其他元素上识别这一点。

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

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

当它们悬停在上面时,这将为类“hoverable”的所有元素提供一类悬停。