最近纠结于一个body满铺的问题,具体状况是:html
body背景图高度固定在2000px左右;
body内内容高度不固定(可能会小于浏览器可视窗口高度,也可能会高于背景图高度即高于2000px);浏览器
稍早前的实现方案是作一块背景div,用js监控滑动位置,再对其进行fixed定位或者absolute定位操做。
具体以下:url
body>.fixed-bg-pic { position: absolute; left: 0; width: 100%; height: 100%; min-width: 1200px; background: url(bg.jpg) center 0px no-repeat; z-index: -1; } body>.fixed-bg-pic.scroll { position: fixed; top: auto; height: 1752px; bottom: 0px; left: 0px; } body>.fixed-bg-pic.bottom { bottom: 210px; height: 1752px; top: auto; }
高度控制spa
_p.bgPicResize = function(){ var scrollH = $(window).scrollTop(), docHeight = $(document).height(); //内容小于背景图 if(docHeight < 1752){ _p._$backPic.removeClass('bottom'); _p._$backPic.removeClass('scroll'); } //从上往下滑动到背景图底部 else if(!_p._$backPic.hasClass('scroll')&&!_p._$backPic.hasClass('bottom')&&scrollH+_p._winHeight>1752) _p._$backPic.addClass('scroll'); //从下往上滑动,背景图触顶时 else if(_p._$backPic.hasClass('scroll')&&scrollH+_p._winHeight<1752){ _p._$backPic.removeClass('scroll'); //从上往下活动,背景图触底时 }else if(!_p._$backPic.hasClass('bottom')&&scrollH>docHeight-242-_p._winHeight){ _p._$backPic.removeClass('scroll'); _p._$backPic.addClass('bottom'); //从下往上滑动,背景图离底时 }else if(_p._$backPic.hasClass('bottom')&&scrollH<docHeight-242-_p._winHeight){ _p._$backPic.addClass('scroll'); _p._$backPic.removeClass('bottom'); } };
后来遇到一个问题:
当body内内容小于浏览器可视窗口高度时,会致使背景div没法满铺整个窗口。
若是给body和html都设置高度100%,这样又会致使背景div没法彻底展开(只能有可视窗口高度)。
最后的解决办法是以下:code
html{ height: 100%; } body{ background: #000; position: relative; min-height: 100%; height: auto; }
后来查阅了一些资料,发现这个问题可以经过background:fixed;来解决。。。(学艺不精,无话可说)
以前的思路还能沿用,不须要单独的背景div,直接将背景放在body上,控制背景的位置就能够了:htm
html{ height: 100%; } body{ position: relative; min-height: 100%; height: auto; background: url(bg.jpg) center 0px fixed no-repeat; background-color: #000; } body.scroll { background-attachment:fixed; background-position:left bottom; } body.bottom { background-attachment: scroll; background-position: center 1542px; }
通常控制背景色body{color:#000}; 浏览器界面都满铺黑色,看似是body标签下背景色起做用了,可是若是body内容不足以撑满浏览器界面时,body高度是没有充满浏览器的,而背景色却可以满铺。图片
body{ background: #fec; padding: 100px; margin: 100px; border: 10px solid #000; }
若是是在html设置背景色,body背景色会被取代,由html背景色填充整个浏览器窗口。ip
html{ background: #cdf; } body{ background: #fec; padding: 100px; margin: 100px; border: 10px solid #000; }
通常状况下大部分浏览器是支持的,当html标签带着background属性时,如:rem
html{ background:#000; } body{ background: url(bg.jpg) center 0px fixed no-repeat; }
这时候,背景图片不能固定,推测缘由应该和上面说的背景色有关系,即html设置背景色后,浏览器的背景色取的是html的背景色,body背景再也不做为浏览器背景,而body没有满铺的缘由。it
关于高度百分之百的做用,通常来讲,知足两个条件:
其一,父标签有高度可寻,就是向上遍历父标签要找到一个定值高度(body,html另外讨论),若是中途有个height为auto或是没有设置height属性,则高度百分比不起做用;
其二,标签自己的属性,若是inline属性的标签,若是没有浮动,zoom,或是绝对定位之类属性是不支持百分比高度的,block或inline-block属性能够说是高度百分比起做用的前提条件之一吧。
默认状况下,body不是高度100%显示的,想让body支持height100%,须要在html上添加height:100%。