獲取元素css樣式的方法
- 元素.style.屬性
- getComputedStyle (元素).屬性名(IE不兼容)
- getComputedStyle是window下一個方法;把對應的元素傳給這個方法
- 他是window上的一個屬性
- 獲取瀏覽器計算的樣式
- 如果是複合屬性名,把-去掉,換成駝峯命名;
- `console.log(getComputedStyle(元素).屬性名)``
- `console.log(getComputedStyle(box).width)``
- `console.log(getComputedStyle(box)[‘width’])``
- currentStyle(只有IE兼容)
- 元素.currentStyle.屬性名
- IE8及以下,用這個方法獲取元素css中設置的樣式;
- 他是元素身上的屬性
function getCss(curEle, attr){
if('getComputedStyle' in window){
return getComputedStyle(curEle)[attr]
}
else {
return curEle.currentStyle[attr]
}
}
---------------------------------------------
function getCss(curEle, attr) {
try {
return getComputedStyle(curEle)[attr]
}catch(e){
return curEle.currentStyle[attr]
}
}
<body>
<div id="box" style="width:800px"></div>
<script>
let box = document.getElementById('box');
console.log('getComputedStyle' in window);
function getCss(curEle, attr){
let val = null;
if('getComputedStyle' in window){
val = getComputedStyle(curEle)[attr]
}
else {
val = curEle.currentStyle[attr]
}
let reg = /^(width|height|top|bottom|left|right|padding|margin|fontSize)&/
if (reg.test(attr)) {
val = parseFloat(val)
}
return val
}
console.log(getCss(box, 'width'))
</script>
</body>
封裝獲取和設置css的方法
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
* {
padding: 0;
margin: 0;
}
#box {
width: 100px;
height: 100px;
background: red;
}
</style>
</head>
<body>
<div id="box"></div>
<script>
function getCss(curEle, attr) {
let val = null
if ('getComputedStyle' in window) {
val = getComputedStyle(curEle)[attr]
} else {
val = curEle.currentStyle[attr]
}
let reg = /^(width|height|top|bottom|left|right|padding|margin|fontSize)$/
if (reg.test(attr)) {
val = parseFloat(val)
}
return val
}
function setCss(curEle, attr, val) {
let reg = /^(width|height|top|bottom|left|right|padding|margin|fontSize)$/
if (reg.test(attr)) {
if (typeof val === 'number') {
val = val + 'px'
}
}
curEle.style[attr] = val
}
function setGroupCss(curEle, obj) {
for (key in obj) {
setCss(curEle, key, obj[key])
}
}
function css() {
let curEle = arguments[0];
let attr = arguments[1];
let val = arguments[2];
if (arguments.length === 2) {
if (typeof attr === 'string') {
return getCss(curEle, attr)
} else {
setGroupCss(curEle, attr)
}
}
else if (arguments.length === 3) {
setCss(curEle, attr, val)
}
}
</script>
</body>
</html>