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:03

pass it a json object:

$(....).css({
    'property': 'value', 
    'property': 'value'
});

http://docs.jquery.com/CSS/css#properties

查看更多
千与千寻千般痛.
3楼-- · 2019-01-01 17:03

You Can Try This

$("p:first").css("background-color", "#B2E0FF").css("border", "3px solid red");
查看更多
心情的温度
4楼-- · 2019-01-01 17:04

Best Way to use variable

var style1 = {
   'font-size' : '10px',
   'width' : '30px',
   'height' : '10px'
};
$("#message").css(style1);
查看更多
梦醉为红颜
5楼-- · 2019-01-01 17:06

please try this,

$(document).ready(function(){
    $('#message').css({"color":"red","font-family":"verdana"});
})
查看更多
像晚风撩人
6楼-- · 2019-01-01 17:07

Try this

$(element).css({
    "propertyName1":"propertyValue1",
    "propertyName2":"propertyValue2"
})
查看更多
还给你的自由
7楼-- · 2019-01-01 17:14

Using a plain object, you can pair up strings that represent property names with their corresponding values. Changing the background color, and making text bolder, for instance would look like this:

$("#message").css({
    "background-color": "#0F0", 
    "font-weight"     : "bolder"
});

Alternatively, you can use the JavaScript property names too:

$("#message").css({
    backgroundColor: "rgb(128, 115, 94)",
    fontWeight     : "700"
});

More information can be found in jQuery's documentation.

查看更多
登录 后发表回答