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