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表示法中,由于名称中的连字符,它们是必须的。


最好使用. addclass()和. removeclass(),即使你有1个或多个样式要更改。它更易于维护和阅读。

如果你真的有冲动做多个CSS属性,那么使用下面的:

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

NB ! 任何带有连字符的CSS属性都需要加引号。 我已经放置了引号,所以没有人需要澄清这一点,代码将是100%的功能。


$('#message').css({ width: 550, height: 300, 'font-size': '8pt' });

将其作为对象传递:

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

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


使用普通对象,可以将表示属性名的字符串与其对应的值配对。改变背景颜色,并使文本粗体,例如,看起来像这样:

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

或者,你也可以使用JavaScript属性名:

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

更多信息可以在jQuery的文档中找到。


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

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

你可以试试这个

$("p:first").css("background-color", "#B2E0FF").css("border", "3px solid red");

请尝尝这个,

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

你也可以将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


最好的方法是使用变量。

var style1 = {
   'font-size' : '10px',
   'width' : '30px',
   'height' : '10px'
};
$("#message").css(style1);

脚本

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

Html

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

如果你想改变多个CSS属性,那么你必须使用下面的对象结构:

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

但是当我们想要改变很多风格时,情况会变得更糟,所以我建议你添加一个类,而不是使用jQuery改变css,并且添加一个类也更易于阅读。

请看下面的例子:

CSS

<style>
    .custom-class{
       font-weight: bold;
       background: #f5f5f5;
       text-align: center;
       font-size: 18px;
       color:red;
    }
</style>

jQuery

$(document).ready(function(){
   $('#message').addclass('custom-class');
});

后一个例子比前一个例子的一个优点是,如果你想在点击某物时添加一些css,并想在第二次点击时删除该css,那么在后一个例子中,你可以使用.toggleClass('custom-class')

在前一个例子中,你必须设置所有的CSS与你之前设置的不同的值,这将是复杂的,所以使用类选项将是更好的解决方案。


你可以使用

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

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

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