很多时候我们会受到一些需求:
1,div 一直置顶
2,div 一直置底
3, 超过一定的位置之后 div 置顶
4, 超过一定位置之后 div 置底
那么下面针对上面的几个问题写几个案例:
一, div 一直在屏幕的上方, 这个倒是容易咱们直接使用 position:fixed; 然后设置他的 top 值和 left 就可以了, 别忘了设置宽度哦
- <div class="top">
- <div class="topf">
- 跟单
- </div>
- </div>
- <style>
- .top,.topf{ height:100px; width:100%;} .topf{ position:fixed; top:0; left:0;
- background:#999; text-align:center; font-size:20px; color:#fff;}
- </style>
点击这里查看 demo -》
二, 这个跟上面的例子是一样的, 我不不多说了
- <div class="bottom">
- <div class="bottomf">
- 跟单
- </div>
- </div>
- <style>
- .bottom,.bottomf{ height:100px; width:100%;} .bottomf{ position:fixed;
- bottom:0; left:0; z-index:12; background:#999; text-align:center; font-size:20px;
- color:#fff;}
- </style>
三, 这个就比较有意思了, 有些时候咱们的导航在 banner 的下方
如下图:
这时候咱们的需求就出来了, 当咱们的滚动条走到 banner 图的底部的时候需要把 nav 的部分悬挂 (position:fixed; top:0);
这时候咱们就得计算了, 先获取 nav 到 document 顶部的距离, 然后在获取滚动条的长度, 相减就能得到 Windows 的顶部的距离, 当两者的相减 <=0 的时候悬挂.
html 代码如下
- <div class="center">
- <div class="centerf">
- 跟单 www.gendan5.com
- </div>
- </div>
CSS 代码如下:
- <style>
- .center{ position:relative; z-index:12;} .center,.centerf{ height:100px;
- width:100%;} .centerf{ background:#666; text-align:center; font-size:20px;
- color:#fff;} .on{ position:fixed; top:0; left:0; z-index:12;} .onm{ position:fixed;
- bottom:0; left:0; z-index:12;}
- </style>
JS 代码如下:
- <script type="text/javascript">
- $(function () {
- function divtop(){
- var boxTop = $('.center').offset().top;
- var scrTop = $('body,html').scrollTop();
- // 头部定位
- if ((boxTop - scrTop) <0){
- if ($('.centerf').hasClass('on')){
- }else{
- $('.centerf').addClass('on')
- }
- }else{
- if ($('.centerf').hasClass('on')){
- $('.centerf').removeClass('on')
- }else{
- }
- };
- };
- divtop();
- $(Windows).scroll(function () {
- divtop();
- });
- $(Windows).resize(function(){
- divtop();
- });
- });
- </script>
四, 还有超过一定位置之后 div 置底
HTML 代码:
- <div class="center">
- <div class="centerf">
- 跟单 www.gendan5.com
- </div>
- </div>
CSS 代码:
- <style>
- .center{ position:relative; z-index:12;} .center,.centerf{ height:100px;
- width:100%;} .centerf{ background:#666; text-align:center; font-size:20px;
- color:#fff;} .onm{ position:fixed; bottom:0; left:0; z-index:12;}
- </style>
JS 代码:
- <script type="text/javascript">
- $(function () {
- function divbottm(){
- var boxTop = $('.center').offset().top;
- var scrTop = $('body,html').scrollTop();
- var winHei = $(Windows).height();
- // 头部定位
- if((boxTop - scrTop - winHei + 100) <0){
- if ($('.centerf').hasClass('onm')){
- }else{
- $('.centerf').addClass('onm')
- }
- }else{
- if ($('.centerf').hasClass('onm')){
- $('.centerf').removeClass('onm')
- }else{
- }
- }
- };
- divbottm();
- $(Windows).scroll(function () {
- divbottm();
- });
- $(Windows).resize(function(){
- divbottm();
- })
- });
- </script>
看到代码很多人都会有一个疑问, 为什么 scroll 和 resize 时间中再执行一遍? 这是因为有些人在浏览网页的时候会改变浏览器的大小的缘故, 当浏览器的大小有变化的时候咱们带再次计算数值, 然后进行调整, 好了, 完毕
来源: http://www.bubuko.com/infodetail-3204009.html