溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

通過jQuery在頁面中固定導航欄的方法

發(fā)布時間:2020-08-29 13:52:53 來源:億速云 閱讀:335 作者:小新 欄目:web開發(fā)

這篇文章主要介紹通過jQuery在頁面中固定導航欄的方法,文中介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們一定要看完!

在做導航欄時除了用我們熟悉的html和CSS來布局以外,還需要用到jQuery中scrollTop和scrollLeft知識,它們主要用于設置或者獲取垂直滾動條的位置,根據(jù)頁面被卷曲的高度來固定導航欄位置,接下來在文章中將和大家詳細分享。

scrollTop

返回或設置匹配元素的滾動條的垂直位置。

$(selector).scrollTop(offset)

offset : 規(guī)定相對滾動條頂部的偏移,以像素為單位,可以寫也可以不寫

例: 獲取頁面被卷曲的高度

$(window).scrollTop();

scrollLeft

返回或設置匹配元素的滾動條的水平位置。

水平位置指的是從其左側滾動過的像素數(shù),

當滾動條位于最左側時,位置是 0。

$(selector).scrollLeft(position)

position:規(guī)定以像素計的新位置,可以寫也可以不寫

滾動條的水平位置指的是從其左側滾動過的像素數(shù)。當滾動條位于最左側時,位置是 0。

例:獲取頁面被卷曲的寬度

$(window).scrollLeft();

案例分享:固定百度搜索欄

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
*{
padding:0;
margin:0;

}
.all{
width:100%;
height:2000px;
}
.box{
width:100%;
height:75px;
background-color: #fff;
border: 1px solid #ccc;
position: relative;
}
.sousu-left img{
position: absolute;
top:20.5%;
left:28.45%;
}
.box1{width:536px;
      height: 41px;
      border:1px solid #ccc;
      margin:16px auto;
  }

.sousu-right span{
width:140px;
height:41px;
border:1px solid #ccc;
color:#fff;
background-color:rgb(51,136,255);
text-align: center;
line-height: 41px;
font-size:14px;
position: absolute;
right:28.64%;
top:19.69%;
      }
  .fixed{
   position: fixed;
   left:0;
   top:0;
  }
</style>
</head>
<body>
<div>
<div>
<!-- 定義左邊和右邊兩個盒子 -->
<div>
<img src="images/logo_top_86d58ae1.png">
<div></div>
</div>
<div>
<span>百度一下</span>
</div>
</div>
</div>
<script src="jquery/jquery-1.12.4.js"></script>
<script>
$(function(){
$(window).scroll(function(){
if($(window).scrollTop()>=$(".box").height())判斷當卷曲的高度大于box高度時給box添加一個fixed屬性,使它固定在頂部
{
$(".box").addClass("fixed");
}
else{
$(".box").removeClass("fixed");如果小于則移除class屬性
}
})
})
</script>
</body>
</html>

通過jQuery在頁面中固定導航欄的方法

以上是通過jQuery在頁面中固定導航欄的方法的所有內容,感謝各位的閱讀!希望分享的內容對大家有幫助,更多相關知識,歡迎關注億速云行業(yè)資訊頻道!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內容。

AI