jQuery 如何通过jquery向选择器添加样式。?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16271667/
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 add style to selector via jquery.?
提问by Cooldharma06
Will the following code work?
下面的代码会起作用吗?
var htmlattri="background-color:red;";
$('a').css("style",htmlattri);
If not, what is the correct solution?
如果不是,正确的解决方案是什么?
回答by Blender
You could add it to the style
attribute:
您可以将其添加到style
属性中:
$('a').attr('style', htmlattri);
But I would use .css()
:
但我会使用.css()
:
$('a').css('background-color', 'red');
Or better yet, do it with a stylesheet and just use .addClass()
.
或者更好的是,使用样式表进行操作,然后使用.addClass()
.
回答by belens
You were almost there. You have to give the parameter name and value seperately: $('a').css("background-color","red");
你快到了。您必须分别给出参数名称和值:$('a').css("background-color","red");
回答by Andrei
Try this:
尝试这个:
$("a").css("background-color","red");
Or
或者
var style ="background-color:red;";
$("a").attr("style", style);
回答by Amit
Use this
用这个
$('a').css('background-color','red');
OR you can use also this type
或者你也可以使用这种类型
$('a').css({background-color:'red'});
回答by dBags
This doesn't use jQuery but allows adding style to a document.
这不使用 jQuery,但允许向文档添加样式。
var styleSheet = document.createElement( 'STYLE' ) ;
styleSheet.innerHTML += '.myclass{ color:red; }' ;
styleSheet.innerHTML += '.yourclass{ color:blue; }' ;
document.body.appendChild( styleSheet ) ;
See https://www.w3.org/wiki/Dynamic_style_-_manipulating_CSS_with_JavaScript
见https://www.w3.org/wiki/Dynamic_style_-_manipulating_CSS_with_JavaScript
回答by Ram Singh
try the following code:
试试下面的代码:
$('a').css('background-color','red');
$('a').css('background-color','red');
回答by NINCOMPOOP
$('a').css('backgroundColor': 'red');
回答by Roopendra
You can directly achieve this by doing this:
您可以通过执行以下操作直接实现此目的:
$('a').css("background-color",red);
But you shouldn't do this directly on hyperlink. You should create a class or Id and add that class CSS on particular class or id.
但是您不应该直接在超链接上执行此操作。您应该创建一个类或 Id 并在特定类或 id 上添加该类 CSS。
HTML:-
HTML:-
<a href="#" class="link" id="link">Test</a>
Jquery:-
jQuery:-
$('#link').css("background-color",red);