1. 程式人生 > 實用技巧 >js和jquery設定css樣式的幾種方法

js和jquery設定css樣式的幾種方法

一、js設定樣式的方法

1. 直接設定style的屬性 某些情況用這個設定 !important值無效

element.style.height = '50px';

2. 直接設定屬性(只能用於某些屬性,相關樣式會自動識別)

 element.setAttribute('height',50);
 element.setAttribute('height',50px');

3. 設定style的屬性

element.setAttribute('style', 'height: 100px !important');

4. 使用setProperty如果要設定!important,推薦用這種方法設定第三個引數

element.style.setProperty('height', '300px', 'important');

5. 改變class 比如JQ的更改class相關方法

因js獲取不到css的偽元素,所以可以通過改變偽元素父級的class來動態更改偽元素的樣式

element.className = 'blue';
element.className += 'blue fb';

6. 設定cssText

element.style.cssText = 'height: 100px !important';
element.style.cssText += 'height: 100px !important';

廣州vi設計公司 http://www.maiqicn.com 我的007辦公資源網 https://www.wode007.com

二、jquery設定樣式的幾種方法

1、設定所有匹配元素的指定 CSS 屬性 不支援屬性名稱簡寫(如border和background)

$(selector).css(name,value)

2、使用函式來設定 CSS 屬性

$(selector).css(name,function(index,value))

$("button").click(function(){
   $("p").css("color",function(){return "red";});
});

name:必需。規定 CSS 屬性的名稱。該引數可包含任何 CSS 屬性,比如 "color";

function(index,value):規定返回 CSS 屬性新值的函式。index - 可選。接受選擇器的 index 位置;value - 可選。接受 CSS 屬性的當前值

3、設定多個 CSS 屬性/值對

$(selector).css({property:value, property:value, ...})
$("p").css({"color":"white","background-color":"#98bf21", "font-family":"Arial", "font-size":"20px","padding":"5px"});