如何使用带有此代码的 jquery 更改 css 属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9285533/
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
How to change css property using jquery with this code
提问by Josh
"#business" is currently set to background: #323232; How can I change it to #000; after I click on "#business" and back to 323232 once the menu is closed?
“#business”当前设置为背景:#323232;我怎样才能把它改成#000;在单击“#business”并在菜单关闭后返回 323232 之后?
$(document).ready(function() {
$("#business").click(function(){
jQuery.fx.off = true;
$("#businessmenu").toggle("");
});
$('html').click(function() {
$("#businessmenu").hide("");
});
$('#business').click(function(event){
event.stopPropagation();
});
});
Here is the html:
这是html:
<a href="#" id="business">Biz name</a>
<div id="businessmenu">
<a href="help.html">Help</a>
</div>
回答by James Allardice
You can use the css
method to change a CSS property (or multiple properties if necessary):
您可以使用该css
方法来更改 CSS 属性(如果需要,也可以更改多个属性):
$("#business").click(function(event){
jQuery.fx.off = true;
$("#businessmenu").toggle("");
$(this).css("background-color", "#000");
event.stopPropagation();
});
$('html').click(function() {
$("#businessmenu").hide();
$("#business").css("background-color", "#323232");
});
Note that I've combined the 2 event listeners you had bound to #business
as it's makes no difference to just bind the one.
请注意,我已将您绑定的 2 个事件侦听器组合在一起,#business
因为仅绑定一个没有区别。
As a side note, is there a reason you are passing an empty string to hide
? That shouldn't be necessary.
作为旁注,您是否有理由将空字符串传递给hide
?那应该没有必要。
回答by Rorchackh
If you want to change the background of an element (in your case "#business") to a color, you simply do:
如果要将元素的背景(在您的情况下为“#business”)更改为颜色,您只需执行以下操作:
$("#business").css({
"background": "#000"
});
But I am not sure what you mean by the "menu", you should probably show us the code of your HTML!
但是我不确定您所说的“菜单”是什么意思,您应该向我们展示您的 HTML 代码!
回答by JaredPar
The css
function is used for changing CSS properties like background.
该css
函数用于更改背景等 CSS 属性。
$('html').click(function() {
$('#businessmenu').hide("");
$('#busniessmenu').css('background-color', '#323232');
});
$('#business').click(function(event){
event.stopPropagation();
$(this).css('background-color', '#000');
});