css()方法獲取或設(shè)置所選元素的一個(gè)或多個(gè)樣式屬性。
當(dāng)使用css()方法獲取屬性值時(shí),它將返回第一個(gè)選定元素的值。
使用css()方法設(shè)置屬性值時(shí),它將為所有選定元素設(shè)置一個(gè)或多個(gè)屬性/值對(duì)。
同樣,jQuery可以同等地解釋多詞屬性的CSS和DOM格式。例如,jQuery可以理解css(“ background-color”)和css(“ backgroundColor”)并返回正確的值。
但是,不完全支持速記簡(jiǎn)寫(xiě)CSS屬性(例如“background”,“margin”和“border”),并且在不同的瀏覽器中可能會(huì)產(chǎn)生不同的結(jié)果。
獲取CSS屬性值:
$(selector).css(property)
設(shè)置CSS屬性和值:
$(selector).css(property, value)
設(shè)置多個(gè)CSS屬性和值:
$(selector).css({property:value, property:value, ...})使用函數(shù)設(shè)置CSS屬性和值
$(selector).css(property, function(index, currentValue))
單擊獲取DIV的背景色:
$("div").click(function(){
$(this).css("background-color");
});測(cè)試看看?/?設(shè)置所有段落的color屬性:
$("button").click(function(){
$("p").css("color", "blue");
});測(cè)試看看?/?設(shè)置多個(gè)CSS屬性和值:
$("button").click(function(){
$("p").css({
"color": "white",
"font-size": "1.3em",
"background-color": "#4285f4",
"padding": "20px"
});
});測(cè)試看看?/?獲取單擊的DIV的寬度,高度,顏色和背景色:
$("div").click(function(){
let html = ["被點(diǎn)擊的div具有以下樣式:"];
let styleProps = $(this).css(["width", "height", "color", "background-color"]);
$.each(styleProps, function(prop, value) {
html.push(prop + ": " + value);
});
$("#result").html(html.join("<br>"));
});測(cè)試看看?/?使用函數(shù)設(shè)置CSS屬性和值:
$("button").click(function(){
$("p").css("padding", function(i, val){
return i + 25;
});
});測(cè)試看看?/?單擊按鈕時(shí),增加所有段落的填充(使用功能):
$("button").click(function(){
$("p").css({
padding: function(i, val){
return parseFloat(val) * 1.2;
}
});
});測(cè)試看看?/?| 參數(shù) | 描述 |
|---|---|
| property | 指定CSS屬性的名稱 |
| value | 指定CSS屬性的值 |
| function(index, currentValue) | 指定一個(gè)函數(shù),該函數(shù)返回CSS屬性的值
|