javascript jquery:向现有样式添加样式属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23331635/
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: add a style attribute to existing style
提问by Sharath
Add a style attribute to existing style properties
将样式属性添加到现有样式属性
I have a div element:
我有一个 div 元素:
<div id="permissions" style="clear: both; float: left;">
I want to set border on onsubmit event:
我想在 onsubmit 事件上设置边框:
<div id="permissions" style="clear: both; float: left; border: 1px #F00 solid; ">
Is there a way to do this: Append new style attribute (border) to existing styles (with out reading existing styles)?
有没有办法做到这一点:将新的样式属性(边框)附加到现有样式(无需阅读现有样式)?
采纳答案by acarlon
As an alternative to manipulating the style directly you could have a css class:
作为直接操作样式的替代方法,您可以拥有一个 css 类:
.submitted
{
border: 1px #F00 solid;
}
Then using jQuery:
然后使用jQuery:
$('#permissions').addClass('submitted');
Then to remove:
然后删除:
$('#permissions').removeClass('submitted');
Then if you want to reuse the same approach elsewhere, you can just use the submitted
class. Also if you want to extend the class (e.g. change the color) you can just edit the submitted
class.
然后,如果您想在其他地方重用相同的方法,则可以使用submitted
该类。此外,如果您想扩展该类(例如更改颜色),您可以只编辑submitted
该类。
回答by Rajender Verma
You can add style to existing style or override existing style like this.
您可以将样式添加到现有样式或像这样覆盖现有样式。
var style =$('#permissions').attr('style'); //it will return string
//on submit update style as
style += ';border: 1px #F00 solid;';
$('#permissions').attr('style',style);
It will not affect your existing style and will add your new style to existing one even if you'll have to override any other property as well.
它不会影响您现有的样式,并且会将您的新样式添加到现有样式,即使您还必须覆盖任何其他属性。
回答by Amit Joki
You can do this:
你可以这样做:
$('form').submit(function(){
$('#permissions').css("border","1px #F00 solid");
});
回答by lolcaks
You can use the css() method of jquery:
您可以使用 jquery 的 css() 方法:
$('#permissions').css('border','1px #000 dashed');