2017-12-20 JS 盒子模型

1.client.html

clientWidth/clientHeight:width/height+左右/上下padding
clientLeft/clientTop:左/上边框宽度

2.scroll:主要看溢出没有.能够作出水平滚动的模型,函数

scrollWidth:若是内容没有溢出,跟clientWidth同样的,若是内容有溢出表示真实内容的宽+左padding
scrollHeight:若是内容没有溢出,跟clientHeight同样的,若是内容有溢出表示真实内容的高+上padding
scrollLeft:横向滚动的距离
scrollTop:滚动条滚上去的距离

3.offsetthis

offsetWidth/offsetHeight:clientWidth/clientHeight+左右/上下border
offsetLeft/offsetTop:距离父级参照物的左/上偏移量
offsetParent:父级参照物

注意::13个属性中,只有scrollTop与scrollLeft能够获取和设置,其余能够获取,不能够设置.htm

getComputedStyle(box)//能够获取styley内的box的样式,而不须要写在行内

2.1扩展:水平滚动代码seo

var container=document.getElementsByClassName("container")[0];
var boxBegin=document.getElementsByClassName("box-begin")[0];
//获取一个盒子的宽
var boxW=boxBegin.offsetWidth;
//注意:container有滚动条全部操做的是container的scrollLeft
function fn() {
//container.scrollLeft一旦大于等于boxW的时候,从0开始,其余状况正常增长便可
this.scrollLeft>=boxW?this.scrollLeft=0:this.scrollLeft++;
}
//设置一个定时器让container的scrollLeft不断增长
var timer=window.setInterval(function () {
fn.call(container)
},20);
//给 container绑定鼠标滑过事件,鼠标放上中止定时器
container.onmouseover=function () {
window.clearInterval(timer);
};
//鼠标移开 container,定时器继续
container.onmouseout=function () {
//this container
timer=window.setInterval(()=>{fn.call(this)},20);
}

扩展:回到顶部模型和获取offset的模型能够封装成两个函数放在一个js中,html中引用事件

let $=(function () {
function win(attr,value) {
if(arguments.length==1){
return document.documentElement[attr]||document.body[attr];
}else if(arguments.length==2) {
document.documentElement[attr]=value;
document.body[attr]=value;
}
}
function offset(curEle) {
var L=curEle.offsetLeft;
var T=curEle.offsetTop;
var P=curEle.offsetParent;
while (P){
if(!/MSIE 8/.test(window.navigator.userAgent)){
L+=P.clientLeft;
T+=P.clientTop;
}
L+=P.offsetLeft;
T+=P.offsetTop;
P=P.offsetParent;
}
}
return{
win:win,
offset:offset
}
})();
  

该方法用在回到顶部的案例中get

//需求:当网页滚上去的距离超过一屏了此时显示upvar body=document.body;var up=document.getElementById("up");//获取一屏的高var H=$.win("clientHeight");var timer=null;body.onscroll=function () {    //判断滚上去的距离是否大于等于H,一旦大于等于H,此时让up显示    if($.win("scrollTop")>=H){        up.style.display="block";    }else {        up.style.display="none";    }};//给up绑定点击事件,让 scrollTop值不断减少到0,设置定时器让其减少,当scrollTop值小于等于0时候清除定时器up.onclick=function () {    timer=setInterval(function () {        //先获取scrollTop值        var t=$.win("scrollTop");        //将这个值减少再赋值给scrollTop        $.win("scrollTop",t-=100);        //判断临界值        if(t<=0){            clearInterval(timer)        }    },10)}
相关文章
相关标签/搜索