【发布时间】:2012-07-10 18:06:37
【问题描述】:
我有一组按钮,当鼠标悬停时,它们会改变颜色。这些的 CSS 以这种方式运行:
#navsite ul li button
{
height: 60px;
width: 60px;
background-image: -moz-linear-gradient(bottom, black, #4D4D4D);
box-shadow: 2px 3px 3px 2px #888888;
border-radius: 15px;
border-color: 359ABC;
cursor: pointer;
margin-left: 5px;
margin-right: 5px;
vertical-align: bottom;
}
#navsite ul li button:hover
{
height: 60px;
width: 60px;
background-image: none;
background-color: #00054C;
box-shadow: 2px 3px 3px 2px #888888;
border-radius: 15px;
border-color: 359ABC;
cursor: pointer;
margin-left: 5px;
margin-right: 5px;
vertical-align: bottom;
}
然后,JavaScript 会在点击时更改颜色(下面的示例涵盖了五个按钮之一,每个按钮都有一个功能,请见谅):
function dude()
{
document.getElementById("dude").hidden=false;
document.getElementById("bob").hidden=true;
document.getElementById("ted").hidden=true;
document.getElementById("joe").hidden=true;
document.getElementById("fred").hidden=true;
document.getElementById("button1").style.background='#00054C';
document.getElementById("button2").style.background='-moz-linear-gradient(bottom, black, #4D4D4D)';
document.getElementById("button3").style.background='-moz-linear-gradient(bottom, black, #4D4D4D)';
document.getElementById("button4").style.background='-moz-linear-gradient(bottom, black, #4D4D4D)';
document.getElementById("button5").style.background='-moz-linear-gradient(bottom, black, #4D4D4D)';
}
我现在的问题是这个脚本激活后,CSS规则#navsite ul li button:hover不再适用,根本没有鼠标悬停效果。如何修复脚本,使其不会阻止 CSS 正常运行?
编辑:我是否应该考虑将该 CSS 子句转换为脚本本身的一部分?我发现将脚本转换为 CSS 子句是不可能的,我希望使用最少的资源。
我更改了脚本,使其列出活动和非活动类,而不是列出颜色本身。不过,它仍然相当笨重。关于如何压缩它的任何想法?
【问题讨论】:
-
该代码看起来像你复制和粘贴相同的东西多次更改不同的按钮,有更有效的方法。
-
您在 CSS 中设置 bakground-color 和 background-image,但在脚本中设置背景。也许尝试改变脚本来设置 style.backgroundImage 和 style.backgroundColor ?
-
请记住,来自 JS 的样式是内联输入的,其优先级高于样式表。
-
顺便说一下,上面示例中的很多 CSS 是不必要的。 #navsite ul li button:hover 仍然是 #navsite ul li 按钮,因此您无需重复所有未更改的属性。在您的示例中, :hover 位中仅需要 background-image 和 background-color 属性。
标签: javascript css