如何恢复“默认”按钮样式

时间:2010-11-30 13:40:52

标签: jquery css internet-explorer button

我有一个保存按钮,当用户将鼠标悬停在它上面时,我会更改一些样式 - 例如:

$('.saveButton').mouseover(function() {
   $(this).css("background-color", "red");
   $(this).parents('fieldset').css("border", "2px solid red");
});

当鼠标离开按钮时,我想恢复原始:

$('.saveButton').mouseout(function() {
   $(this).css("background-color", "#EEE");
   $(this).parents('fieldset').css("border", "1px solid gray");
});

然而,不考虑默认按钮背景颜色是否为#EEE,当此代码执行时,按钮失去其圆形外观,并具有方角。

是否可以这样做?

5 个答案:

答案 0 :(得分:7)

我建议不要直接设置属性,而是设置类/类:

$('.saveButton').mouseover(function() {
   $(this).addClass('highlight');
   $(this).parents('fieldset').addClass('highlight');
}).mouseout(function() {
   $(this).removeClass('highlight');
   $(this).parents('fieldset').removeClass('highlight');
});

.saveButton.highlight { /* Double class selector is broken in IE6 */
   background-color: red;
}

fieldset.highlight {
  border: 1px solid red;
}

如果由于某种原因您不想这样做,而不是将特性设置为特定值,而是设置为空字符串。这应该“删除”该属性:

$('.saveButton').mouseout(function() {
   $(this).css("background-color", "");
   $(this).parents('fieldset').css("border", "");
});

答案 1 :(得分:4)

是的,使用一个类和一些css:

/* in style.css */
.over {
    border: 2px solid red;
}
.over .saveButton {
    background-color: red;
}

然后只需将此类添加/删除到父字段集:

$('.saveButton').mouseover(function() {
     $(this).parents('fieldset').addClass('over');
}).mouseout(function() {
     $(this).parents('fieldset').removeClass('over');
});

删除该类将恢复该按钮及其之前的字段状态。


作为一个好习惯 - 最好在css中保留演示文稿(看起来如何)并使用javascript在它们之间切换 - 这样管理起来要容易得多。

答案 2 :(得分:2)

这将更适合CSS :hover伪clas。而且比javascript快得多。

.fieldset-class:hover { border: 2px solid red;}
.saveButton:hover { background-color:red;}

只要您只需要在mouseover / mouseout事件上更改CSS,请使用此方法。

这是一个live example from Soh Tanaka的CSS :hover。吧上那些弹出工具提示?纯CSS。

<强>更新
我的CSS中存在与您的问题模型有关的缺陷。即使您没有悬停在按钮上,这也会导致字段集上的悬停触发。我会在CSS中使用第二行.saveButton:hover,并使用JavaScript作为字段集悬停,使用类,正如其他答案所指出的那样。

(Actaully 会改变我的问题模型以接受纯CSS解决方案,但我离题了......)

答案 3 :(得分:0)

最好的方法是为鼠标悬停时添加的样式创建一个CSS类,并使用“addClass”将其添加到jQuery中。然后你可以使用“removeClass”删除你的临时样式。

答案 4 :(得分:0)

是的,您可以为mouseEnter设置一个类,使bg颜色和边框颜色为红色。

您可以为事件使用toggleClass,以便切换添加和删除类的事件,并始终恢复默认按钮。

相关问题