DOM 补充知识

 

DOM Element对象知识补充 CSS操作 1、操作内联样式 a、设置内联样式 语法:元素.style.样式属性名 = 样式属性值 例:

 

 

    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);

2、获取最终样式 1、getComputedStyle(); 语法:window.getComputedStyle(元素,null).样式属性名 2、currentStyle 语法:元素.currentStyle.属性样式名 3、兼容方案: function getStyle(elem,attrName){ //判断 window.getComputedStyle() 方法是否存在 if (window.getComputedStyle){ return getComputedStyle(elem,null)[attrName]; }else{ return elem.currentStyle[attrName]; } } 3、获取元素尺寸 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-width

posted @ 2017-08-27 20:53  毁梦  阅读(158)  评论(0编辑  收藏  举报