position: sticky;實(shí)現(xiàn)banner吸頂功能

原創(chuàng)聲明

本文系作者辛苦碼字所得,歡迎分享和轉(zhuǎn)載,但請(qǐng)?jiān)诿黠@位置注明作者的如下信息:
筆名:來(lái)碗雞蛋面
簡(jiǎn)書(shū)主頁(yè):http://www.itdecent.cn/u/4876275b5a73
郵箱:job_tom@foxmail.com
CSDN ID:tom_wong666

需求:

實(shí)現(xiàn)banner吸頂功能,即nav,bannner,content上下三欄布局頁(yè)面上,向上滾動(dòng)過(guò)程中:
1,nav會(huì)消失逐漸;
2,banner會(huì)逐漸向上移動(dòng),直到貼到body頂部然后固定在body頂部;
3,content會(huì)向上走并逐漸被隱藏;

分析:

1,js+css實(shí)現(xiàn):nav static定位, banner absolute定位(加top等于nav高度), content static定位(加margin-top 等于banner高度),依據(jù)body的scrollTop值動(dòng)態(tài)調(diào)整banner absolute定位的top值;這樣做,缺點(diǎn)是邏輯復(fù)雜,設(shè)備資源消耗大,以及頁(yè)面容易抖動(dòng)。
2,css實(shí)現(xiàn):position: sticky;可以規(guī)避以上缺點(diǎn);缺點(diǎn)是IE不兼容,不過(guò)親測(cè)Edge是支持的,畢竟Edge已經(jīng)擁抱Chromium了。

position: sticky說(shuō)明--參閱MDN解釋如下:

// 粘性定位可以被認(rèn)為是相對(duì)定位和固定定位的混合。元素在跨越特定閾值前為相對(duì)定位,之后為固定定位。例如:

#one { position: sticky; top: 10px; }
// 在 viewport 視口滾動(dòng)到元素 top 距離小于 10px 之前,元素為相對(duì)定位。之后,元素將固定在與頂部距離 10px 的位置,直到 viewport 視口回滾到閾值以下。

// 粘性定位常用于定位字母列表的頭部元素。標(biāo)示 B 部分開(kāi)始的頭部元素在滾動(dòng) A 部分時(shí),始終處于 A 的下方。而在開(kāi)始滾動(dòng) B 部分時(shí),B 的頭部會(huì)固定在屏幕頂部,直到所有 B 的項(xiàng)均完成滾動(dòng)后,才被 C 的頭部替代。

須指定 top, right, bottom 或 left 四個(gè)閾值其中之一,才可使粘性定位生效。否則其行為與相對(duì)定位相同。

代碼示例:

<html lang="zh-en">
    <head>
      <style>
        body {
          position: relative;
        }
        .nav {
          width: 100%;
          height: 10%;
          background: red;
          position: sticky;
          z-index: 100;
          top: 0;
        }        
        .banner {
          width: 100%;
          height: 10%;
          background: blue;
          position: sticky;
          z-index: 100;
          top: 0;
        }
        .content {
          width: 100%;
          height: 10%;
          background: gray;
          position: relative;
          z-index: 0;          
        }
      </style>
    </head>
    <body>
      <div class="nav">nav</div>
      <div class="banner">banner
        <br/>
        向上滾動(dòng)過(guò)程中:1,nav會(huì)消失逐漸;2,banner會(huì)逐漸向上移動(dòng),直到貼到body頂部然后固定在body頂部;3,content會(huì)向上走并逐漸被隱藏;
      </div>
      <div class="content">content1</div>
      <div class="content">content2</div>
      <div class="content">content3</div>
      <div class="content">content4</div>
      <div class="content">content5</div>
      <div class="content">content6</div>
      <div class="content">content7</div>
      <div class="content">content8</div>
      <div class="content">content9</div>
      <div class="content">content10</div>
      <div class="content">content11</div>
      <div class="content">content12</div>
    </body>
</html>

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容