我正在尝试动态调整我的 CSS。这是我的 CSS:
.red_button {
background:url(record.png);
padding: 19px 251px;
cursor: pointer;
background-repeat: no-repeat;
}
.red_button:hover {
background:url(record-hover.png);
cursor: pointer;
background-repeat: no-repeat;
}
点击后变成这样:
function recordStarted() {
started = true;
$("#red_button").css("background","url(stop.png)");
$("#red_button").css("background-repeat","no-repeat");
}
但是如果我尝试用 $("#red_button:hover").css("background","url(stop.png)");
这样的东西来改变 :hover 属性只是改变背景(不是悬停背景)。那么最好的方法是什么?我已经尝试了一些不同的东西,比如使用 jQuery,但没有任何效果。
最佳答案
请不要这样做,除非绝对需要,否则请使用 CSS 类。这会将你所有的样式分离到它所属的 CSS 中,同时清理你的 JS。
CSS
#red_button.clicked {
/* Applied when the button is clicked and NOT hovered */
}
#red_button.clicked:hover {
/* Applied when the button is clicked and hovered */
background: url(stop.png);
background-repeat: no-repeat;
}
JS
function recordStarted() {
started = true;
$("#red_button").addClass("clicked");
}
我还注意到您指的是 CSS 中的 .red_button
类,但 JS 中的 #red_button
ID,您可能是说它们都是 ID?
编辑:更改规则以在单击和悬停时应用。
这是一个简单的样式示例:http://jsfiddle.net/BMmsD/
关于javascript - 使用 Javascript/jquery 更改 CSS 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15240552/