How to define multiple CSS attributes in jQuery?

2019-01-01 16:43发布

Is there any syntactical way in jQuery to define multiple CSS attributes without stringing everything out to the right like this:

$("#message").css("width", "550px").css("height", "300px").css("font-size", "8pt");

If you have, say, 20 of these your code will become hard to read, any solutions?

From jQuery API, for example, jQuery understands and returns the correct value for both

.css({ "background-color": "#ffe", "border-left": "5px solid #ccc" }) 

and

.css({backgroundColor: "#ffe", borderLeft: "5px solid #ccc" }).

Notice that with the DOM notation, quotation marks around the property names are optional, but with CSS notation they're required due to the hyphen in the name.

标签: jquery css
12条回答
千与千寻千般痛.
2楼-- · 2019-01-01 17:17
$('#message').css({ width: 550, height: 300, 'font-size': '8pt' });
查看更多
唯独是你
3楼-- · 2019-01-01 17:19
$("#message").css({"width" : "550px", "height" : "300px", "font-size" : "8pt"});

Also, it may be better to use jQuery's built in addClass to make your project more scalable.

Source: How To: jQuery Add CSS and Remove CSS

查看更多
回忆,回不去的记忆
4楼-- · 2019-01-01 17:23

Agree with redsquare however it is worth mentioning that if you have a two word property like text-align you would do this:

$("#message").css({ width: '30px', height: '10px', 'text-align': 'center'});
查看更多
余欢
5楼-- · 2019-01-01 17:23

try this:

$(IDname).css({ "background":"#000", "color":"#000" })

i.e hello is id in div.

<div id="hello"></div>

查看更多
孤独寂梦人
6楼-- · 2019-01-01 17:27

Better to just use .addClass() even if you have 1 or more. More maintainable and readable.

If you really have the urge to do multiple CSS properties then use the following:

.css({
   'font-size' : '10px',
   'width' : '30px',
   'height' : '10px'
});

NB!
Any CSS properties with a hyphen need to be quoted.
I've placed the quotes so no one will need to clarify that, and the code will be 100% functional.

查看更多
像晚风撩人
7楼-- · 2019-01-01 17:27

You can also use attr along with style:

$('#message').attr("style", "width:550; height:300; font-size:8px" );
查看更多
登录 后发表回答