元素樣式控制

2021-12-29 19:45:46 字數 1843 閱讀 7977

樣式屬性通過四種方式可以被新增,他們的優先順序從高到低依次為:

1. inline styles;

2. style sheet rules;

3. html attributes(比如fill,height, width等);

4. html標籤預設定義;

element.style操作的是元素的styleattribute指定的樣式(inline styles)。

getcomputedstyle方法接受兩個引數,第乙個是要查詢的元素,第二個引數可選,值是表示pseudo-element的字串。getcomputedstyle的優勢就是可以獲取pseudo元素的樣式,而style, currentstyle和runtimestyle都不行。但getcomputedstyle返回的所有樣式都是唯讀的。

currentstyle是由樣式表單、inline樣式和htmlattributes決定的,是應用的樣式設定的值,但並不能反映獲取值時渲染所採用的值。比如樣式設定為color:red; display:none,將返回currentstyle.color為red,儘管元素並沒在頁面上渲染。也就是說,currentstyle不受渲染與否的約束。

特點:ie元素獨有,firefox和chrome沒有;currentstyle儲存的是採用的樣式設定,而不是最終值,比如color:green,currenttyle.color返回的依然是green,而不是#00ff00;currentstyle是非同步的,因此頁面還在載入的時候獲取的值可能是過去的值,最好等body已經load成功之後再獲取。element.runtimestyle表示的是由全域性樣式表單、inline樣式和htmlattributes指定的元素級聯樣式。

特點:ie元素獨有,firefox和chrome沒有;runtimestyle儲存的是採用的樣式設定,而不是最終值,比如color:green,currenttyle.color返回的依然是green,而不是#00ff00;修改runtimestyle會影響currentstyle,但不會影響style物件;style和runtimestyle在功能上是相等的;修改style或runtimestyle,都會影響currentstyle。但是,單獨修改style不會影響runtimestyle,同理,單獨修改runtimestyle也不會影響style。

雖然msdn認為runtimestyle和style等價,優先順序相同,經過ie7,ie8,ie9,ie10,ie11實際測試後發現,一旦通過runtimestyle設定某個樣式屬性之後,再通過style物件操作這個屬性就不再起作用。因此,可以等同認為runtimestyle的優先順序比style高。

在ie中,這個方法其實返回的就是currentstyle。

從ie9開始支援這個方法,ie8和低於ie8的ie都不支援。

這是firefox獨有的方法,與getcomputedstyle()的主要區別是getdefaultcomputedstyle只返回使用者**和使用者自定義的原樣式,元素渲染之後,使用者又重新編輯的樣式被忽略。getcomputedstyle才是元素現有的樣式。

1. 首先判斷window有沒有getcomputedstyle方法,如果有,就用這個方法獲取;一般來說,呼叫方式為document.defaultview.getcomputedstyle()。

2. 如果沒有getcomputedstyle方法,針對ie,應該使用currentstyle。

element.removeattribute(style)。

element.style.csstext ='color:red;background-color:blue;border:5px solid black;';

這樣寫的問題是會刪除掉style上原有的所有樣式。

樣式控制v for中的某個元素

你好!這是你第一次使用markdown編輯器所展示的歡迎頁。如果你想學習如何使用markdown編輯器,可以仔細閱讀這篇文章,了解一下markdown的基本語法知識。全新的介面設計,將會帶來全新的寫作體驗 在創作中心設定你喜愛的 高亮樣式,markdown將 片顯示選擇的高亮樣式進行展示 全新的ka...

獲取元素樣式

object.style attr 只可獲取html標籤內的樣式,主要用來設定css,而不可獲取style標籤中的css樣式 ie支援object.currentstyle attr ff支援getcomputedstyle object,false attr 首先是有兩個引數,元素和偽類。第二個引...

獲取元素樣式

1 ele.style ele.style只能獲取寫在元素標籤中的style屬性裡的樣式值,無法獲取到定義在和通重載入進來的樣式屬性 var test document.getelementbyid test 獲取節點的color test.style.color 2 getcomputedstyl...