jQuery中是否有一种语法方法来定义多个CSS属性,而不是像这样把所有的东西都排在右边:

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

如果你有20个这样的代码,你的代码会变得难以阅读,有什么解决方案吗?

例如,通过jQuery API, jQuery可以理解并返回两者的正确值

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

and

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

注意,在DOM表示法中,属性名周围的引号是可选的,但在CSS表示法中,由于名称中的连字符,它们是必须的。


当前回答

请尝尝这个,

$(document).ready(function(){
    $('#message').css({"color":"red","font-family":"verdana"});
})

其他回答

同意redsquare,但值得一提的是,如果你有一个两个字的属性,如文本对齐,你会这样做:

$("#message").css({ width: '30px', height: '10px', 'text-align': 'center'});

你可以使用

$('selector').css({'width:'16px', 'color': 'green', 'margin': '0'});

最好的方法是使用$('selector').addClass('custom-class')和

.custom-class{
width:16px,
color: green;
margin: 0;
}

你也可以将attr和style一起使用:

$('#message').attr("style", "width:550; height:300; font-size:8px" );

试试这个

$(element).css({
    "propertyName1":"propertyValue1",
    "propertyName2":"propertyValue2"
})
$("#message").css({"width" : "550px", "height" : "300px", "font-size" : "8pt"});

此外,最好使用jQuery内置的addClass来使你的项目更具可伸缩性。

jQuery添加CSS和删除CSS