獲取元素css樣式的方法

2021-10-07 18:35:45 字數 2813 閱讀 2916

getcomputedstyle (元素).屬性名(ie不相容)

currentstyle(只有ie相容)

function

getcss

(curele, attr)

else}--

----

----

----

----

----

----

----

----

----

-------

function

getcss

(curele, attr)

catch

(e)}

>

"box"

style

="width

:800px

">

div>

>

let box = document.

getelementbyid

('box');

// 獲取元素的css樣式

// 1、元素.style.width 這是獲取的行內樣式

// console.log(box.style.width) '' // 獲取不到

// 2、getcomputedstyle

// 1、他是window上的乙個屬性

// 2、getcomputedstyle(元素).屬性名

// console.log('getcomputedstyle' in window) // true

// console.log(getcomputedstyle(box).width) // '100px'

// console.log(getcomputedstyle(box)['width']) // '100px'

// console.log(getcomputedstyle(box)['backgroundcolor']) //'rbg(255,0,0)'

// 3、 currentstyle

// 1、這個屬性只在ie下存在

// 2、元素.currentstyle.屬性名

// console.log(box.currentstyle.width);

console.

log(

'getcomputedstyle'

in window)

;/*

封裝乙個獲取scc樣式的方法,

/* 封裝

*/function

getcss

(curele, attr)

else

let reg =

/^(width|height|top|bottom|left|right|padding|margin|fontsize)$/

if(reg.

test

(attr)

)return val

}function

setcss

(curele, attr, val)

} curele.style[attr]

= val

}// setcss(box, 'width', 200)

// setcss(box, 'height', '200px')

// setcss(box, 'backgroundcolor', 'green')

function

setgroupcss

(curele, obj)

}// setgroupcss(box, )

function

css(

)else

}// 如果arguments的legnth是3,那說明你是想單個設定樣式

else

if(arguments.length ===3)

}script

>

body

>

html

>

獲取元素樣式屬性的方法

獲取 的高度1 如果是行內樣式 style可以直接獲取。document.getelementsbytagname div 0 style.height 2 如果是內聯樣式 用style返回的是undefined 需要採用其他方法。由於不同瀏覽器造成相容問題,獲取的方法又不相同。在ie中,採用的是c...

js獲取元素css樣式表中的樣式

情況一 寬高都寫在樣式表裡,即外部樣式或嵌入式樣式,比如 div1。這種情況通過 div1.style.width拿不到寬度,而通過 div1.offsetwidth才可以獲取到寬度。情況二 寬和高是寫在行內中,即內聯式樣式,比如style width 120px 這中情況通過上述2個方法都能拿到寬...

獲取元素的樣式

行間樣式 divid box1 style width 300px height 100px div console log box1 style width 非行間樣式 box2 divid box2 div console log box2 style width getcomputedstyl...