JS中的盒子模型

来源:互联网 发布:电脑截gif软件 编辑:程序博客网 时间:2024/06/04 19:32
//js盒子模型-->浏览器提供一些获取盒子位置信息的属性和方法    //1、clientWidth/clientHeight    //clientWidth:width+左右padding    //clientHeight:height+上下padding    //2、clientTop/clientLeft    //clientTop:上边框的高度    //clientLeft:左边框的宽度    //不存在clientRight和clientBottom,这两属性的是都是undefined    //3、offsetWidth/offsetHeight    //offsetWidth:clientWidth+左右边框    //offsetHeight:clientHeight+上下边框    //高度不设置的话,高度会自适应,height的值就是实际内容的高度    //4、scrollWidth/scrollHeight    //在没有内容溢出的情况下和clientWidth/clientHeight是一样的    //有内容的溢出情况(在每一个浏览器中的值不太一样,加上overflow: hidden和不加还有少许的区别):    //scrollHeight:约等于 真实内容的高度(包含溢出的内容)+上padding    //scrollWidth:约等于 真实内容的宽度(包含溢出的内容)+左padding    //console.log(oDiv.scrollHeight);    //获取当前浏览器一屏幕的宽度和高度    //document.documentElement.clientWidth || document.body.clientWidth;    //document.documentElement.clientHeight || document.body.clientHeight;    //当前所有屏加起来的高度(当前网页的高度)~= document.documentElement.scrollHeight||document.body.scrollHeight    //style设置和获取的都是行内样式,如果行内上没有写这个样式(不管你是否在样式表中写了),我们都获取不到值    //console.log(oDiv.style.width);//-->""    //getComputedStyle:获取经过计算机计算的样式(只要是在页面上的元素,它的样式都是经过计算机计算的样式)    //window.getComputedStyle(要获取样式的元素,当前元素的伪类(一般情况下我们都写null));  -->存储的是一个对象数据类型的值,里面包含了当前这个元素的所有的样式属性,我们如果想获取其中的某一个样式的值    //console.dir(window.getComputedStyle(oDiv, null)["marginLeft"]);    //console.dir(window.getComputedStyle(oDiv, null));    //我们在css中刚开始设置的默认的公共样式,不仅对css编写由帮助,而且对于js也是有帮助的,方便我们对所有浏览器默认的样式值进行统一    //getComputedStyle在IE6~8下不兼容,我们需要用currentStyle来代替(currentStyle只有IE下才能用)    //console.log(oDiv.currentStyle["marginTop"]);    //getComputedStyle/currentStyle 获取的样式的值,数字这种的类别的都是加单位的,例如:"100px",而有些样式的值天生就没有单位,例如:display、opacity、position、zIndex、float...,除了这些还有一些是复合样式的,例如:margin、padding、border...

兼容所有浏览器的获取css的方式

function getCss(curEle, attr) {        var val = null;        if ("getComputedStyle" in window) {            val = window.getComputedStyle(curEle, null)[attr];        } else {            val = curEle.currentStyle[attr];        }        //margin|padding(Top、Left、Right、Bottom)、left、top、bottom、right、width、height        var reg = /^(((margin|padding)?(top|left|bottom|right))|(width|height))$/i;        if (reg.test(attr)) {            if (val.indexOf("%") === -1) {                return parseFloat(val);            }        }        return val;    }
偏移量:当前盒子的外边框距离父级参照物产生的位移我们用offsetParent来获取父级参照物,offsetParent(父级参照物)和parentNode(父亲节点)没有必然的联系页面中的所有的元素默认都在同一个水平面上,父级参照物是当前平面最外面的那个盒子,所以默认情况下,所有元素的父级参照物都是body如果需要改变父级参照物我们只能用position将它的平面关系改变,加了这个属性 则改变了其父级参照物
0 0
原创粉丝点击