美文网首页
js 盒子模型

js 盒子模型

作者: McDu | 来源:发表于2017-08-01 16:39 被阅读10次
    var div = document.getElementsByTagName("div");
    div.attributes.item(0) // HTML5 里的属性  元素的属性
    div.classList.add('test')  // 直接添加一个类
    

    盒子模型属性值

    1. client (只读)

    clientWidth: 内容的可视宽度(width)+ 左右 padding
    clientHeight: 内容的可视高度(height) + 上下 padding
    clientLeft: 左边框的宽度
    clientTop: 上边框的宽度

    box.contentEditable = 'true'   // 让 box 可编辑
    

    2. offset(只读)

    offsetWidth: clientWidth + 左右边框
    offsetHeight: clientHeight + 上下边框
    offsetTop: 当前元素的外边框距离父级参照物的内边距的偏移量。最小值 0 ,最大值:scrollHeight - clientHeight;
    offsetLeft:
    offsetParent: 当前元素的父级参数物

    3. scroll (scrollWidth、scrollHeight 只读,scrollTop、scrollLeft 可修改)

    scrollWidth : 没有内容溢出时, clientWidth 等于 scrollWidth
    scrollHeight : 有内容溢出时,真实内容高度 + 上下填充
    获取到的结果是 “约等于” 的值,同一个浏览器,是否设置 overflow:'hidden',对最终结果是有影响的,不同浏览器中取得的值也是不同的。
    scrollTop: 滚动条拉动过程中,看不到的内容的高度。
    scrollLeft: 滚动条拉动过程中,看不到的内容的宽度。

    2. js 盒子模型取值问题:

    上面的属性值获取的结果都是整数,浏览器在获取结果的时候在真实的结果上进行四舍五入处理。

    3. 关于操作浏览器本身的盒子模型

    获取可视宽度:

     document.documentElement.clientWidth || document.body.clientWidth
     document.documentElement.clientHeight || document.body.clientHeight
    

    页面的真实宽度和高度:

      document.documentElement.scrollWidth || document.body.scrollWidth
      document.doucmentElement.scrollHeight || document.body.scrollHeight
    

    兼容的写法:

    document.documentElement[attr] || document.body[attr]
    

    兼容的方法获取属性值和设置属性值:

    /*
     * 只传递了 attr 参数,说明是获取属性的值,
     * 如果传递 value ,说明是设置值
    */
    function win(attr, value){
      if(typeof value === 'undefined'){
            return document.documentElement[attr]|| document.body[attr]
        }
        document.documentElement[attr] = value;
        document.body[attr] = value;
    }
    

    window.getComputedStyle :获取所有经过浏览器计算后的样式。(IE 6~8 下不兼容,没有 getComputedStyle)

    window.getComputedStyle(当前要操作的对象,伪类),不用写伪类写 null 
    比如获得高度:window.getComputedStyle(div,null).height
    IE6~8 : 可以使用 currentStyle 来获取所以经过浏览器计算过的样式。
    

    border , fontFamily 标准浏览器和 IE 浏览器获取到的结果不同,主要是 getComputedStyle 和 currentStyle 计算的结果不同。可以通过初始化一些样式,避免浏览器之间的差异。

    // 获取当前元素所以经过浏览器计算过的样式中的 [attr] 对应的值
    function getCss(curEle, attr){
      var val = null, reg = null;
      try{
            if('getComputedStyle' in window){
                  val = window.getComputedStyle(curEle, null)[attr];
            } // 这里可以不用 if 
       } catch (e){
            if(attr === "opacity"){
              val = curEle.currentStyle['filter'];
               reg = /^alpha\(opacity=(\d+(?:\.\d+)?)\)$/i;
               val = reg.test(val)?reg.exec(val)[1]/100:1;
            }else{
              val = curEle.currentStyle[attr];
            }  
      }
      reg = /^(-?\d+(\.\d+)?)(px|pt|rem|em)?/i;
      return reg.test(val)?parseFloat(val):val;  //去掉单位
    }
    

    相关文章

      网友评论

          本文标题:js 盒子模型

          本文链接:https://www.haomeiwen.com/subject/qqbokxtx.html