jQuery 切换 CSS?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3337621/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery toggle CSS?
提问by Edd Turtle
I want to toggle between CSS so when a user clicks the button (#user_button
) it shows the menu (#user_options
) and changes the CSS, and when the user clicks it again it goes back to normal. So far this is all I have:
我想在 CSS 之间切换,因此当用户单击按钮 ( #user_button
) 时,它会显示菜单 ( #user_options
) 并更改 CSS,当用户再次单击它时,它会恢复正常。到目前为止,这就是我所拥有的:
$('#user_button').click( function() {
$('#user_options').toggle();
$("#user_button").css({
borderBottomLeftRadius: '0px',
borderBottomRightRadius: '0px'
});
return false;
});
Can anybody help?
有人可以帮忙吗?
回答by Ian Wetherbee
For jQuery versions lower than 1.9 (see https://api.jquery.com/toggle-event):
对于低于 1.9 的 jQuery 版本(参见https://api.jquery.com/toggle-event):
$('#user_button').toggle(function () {
$("#user_button").css({borderBottomLeftRadius: "0px"});
}, function () {
$("#user_button").css({borderBottomLeftRadius: "5px"});
});
Using classes in this case would be better than setting the css directly though, look at the addClass and removeClass methods alecwh mentioned.
在这种情况下使用类会比直接设置 css 更好,请查看 alecwh 提到的 addClass 和 removeClass 方法。
$('#user_button').toggle(function () {
$("#user_button").addClass("active");
}, function () {
$("#user_button").removeClass("active");
});
回答by Ties
I would use the toggleClassfunction in jQuery and define the CSS to the class e.g.
我会在 jQuery 中使用toggleClass函数并将 CSS 定义为类,例如
/* start of css */
#user_button.active {
border-bottom-right-radius: 5px;
border-bottom-left-radius: 5px;
-webkit-border-bottom-right-radius: 5px; /* user-agent specific */
-webkit-border-bottom-left-radius: 5px;
-moz-border-radius-bottomright: 5px;
-moz-border-radius-bottomleft: 5px; /* etc... */
}
/* start of js */
$('#user_button').click(function() {
$('#user_options').toggle();
$(this).toggleClass('active');
return false;
})
回答by alecwh
You might want to use jQuery's .addClassand .removeClasscommands, and create two different classes for the states. This, to me, would be the best practice way of doing it.
您可能想要使用 jQuery 的.addClass和.removeClass命令,并为状态创建两个不同的类。对我来说,这将是最好的做法。
回答by Mohamed CHIBANI
The initiale code must have borderBottomLeftRadius: 0px
初始代码必须有borderBottomLeftRadius: 0px
$('#user_button').toggle().css('borderBottomLeftRadius','+5px');
回答by Munzilla
The best option would be to set a class style in CSS like .showMenu
and .hideMenu
with the various styles inside. Then you can do something like
最好的选择是在 CSS 中设置类样式,.showMenu
并在.hideMenu
其中包含各种样式。然后你可以做类似的事情
$("#user_button").addClass("showMenu");