DOM Element對象知識補充 CSS操做 一、操做內聯樣式 a、設置內聯樣式 語法:元素.style.樣式屬性名 = 樣式屬性值 例:css
let box = document.getElementById("box"); box.style.height = "100px"; box.style.width = "100px"; box.style.backgroundColor = "red"; /*正常寫法應該爲「background-color」,但在此處需用駝峯命名法,寫爲「backgroundColor」,去掉橫線c字母大寫*/ console.log(box); b、設置多個內聯樣式 語法:元素.style.cssText = 樣式 例: <div id="box"></div> let box = document.getElementById("box"); box.style.cssText = "寬;高;背景色"; console.log(box); c、獲取內聯樣式 方式一: 語法:元素.style.樣式屬性名 例: <div id="box" style="height:100px"></div> let box = document.getElementById("box"); console.log(box.style.height); 方式二: 語法:元素.setAttribute("style",樣式); 例: <div id="box"></div> let box = document.getElementById("box"); box.setAttibute("style","background-color:red"); console.log(box); e、獲取內聯樣式 語法:元素.getAttribute("style"); 例: let boxStyle = box.getAttribute("style"); console.log(boxStyle);
二、獲取最終樣式 一、getComputedStyle(); 語法:window.getComputedStyle(元素,null).樣式屬性名 二、currentStyle 語法:元素.currentStyle.屬性樣式名 三、兼容方案: function getStyle(elem,attrName){ //判斷 window.getComputedStyle() 方法是否存在 if (window.getComputedStyle){ return getComputedStyle(elem,null)[attrName]; }else{ return elem.currentStyle[attrName]; } } 三、獲取元素尺寸 a、獲取可見尺寸 .可見高度:clientWidth .可見高度:clientHeight 例: console.log(box.clientWidth); console.log(box.clientHeight); 計算公式: clientWidth = width + padding-left + padding-right b、獲取實際尺寸 .寬度:offsetWidth; .高度:offsetHeight; 例: console.log(box.offsetWidth); console.log(box.offsetHeight); 計算公式: offsetWidth = width + padding-left + padding-right + border-widthspa