div固定顯示的幾種方法


很多時候我們會受到一些需求:

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>
點擊這里查看demo -》

 

三、這個就比較有意思了,有些時候咱們的導航在banner的下方

如下圖:

 

這時候咱們的需求就出來了,當咱們的滾動條走到banner圖的底部的時候需要把nav的部分懸掛(position:fixed; top:0);

這時候咱們就得計算了,先獲取nav到document頂部的距離,然后在獲取滾動條的長度,相減就能得到window的頂部的距離,當兩者的相減<=0的時候懸掛。

html代碼如下

<div class="center">
<div class="centerf">青格勒2132132</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;www.gendan5.com
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();
$(window).scroll(function () {
divtop();
});
$(window).resize(function(){
divtop();
});
});
</script>
點擊這里查看demo -》

 

 

四、還有超過一定位置之后div置底

 

Html代碼:

<div class="center">
<div class="centerf">青格勒2132132</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 = $(window).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();
$(window).scroll(function () {
divbottm();
});
$(window).resize(function(){
divbottm();
})
});
</script>

 

看到代碼很多人都會有一個疑問,為什么scroll和resize時間中再執行一遍?這是因為有些人在瀏覽網頁的時候會改變瀏覽器的大小的緣故,當瀏覽器的大小有變化的時候咱們帶再次計算數值,然后進行調整,好了,完畢


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM