簡體   English   中英

使孩子的div位置固定在滾動條上的div的頂部,並動畫化孩子的身高

[英]Make a child of a div's position fixed to the top of the div on scroll and also animate height of child

我有一個叫做box的div,它的header div是一個孩子。 當div滾動時,我希望將標題div粘貼(固定)在頂部,以便用戶始終可以看到標題。 當用戶向下滾動時,標題的高度應減小以占用更少的空間,但仍允許用戶看到標題內容。 當用戶向上滾動時,標頭應未松開,其高度應類似於頂部時的任何滾動方式。

我不喜歡嘗試向您展示的內容,因為我得到了框相對於文檔的offset 我覺得可能沒有必要,因為可能有CSS解決方案。 是用於整個文檔的滾動。 該演示顯示使用固定位置,並且固定在頁面頂部。 我不能使用固定位置,因為我認為這是針對窗口而不是div的,那么下一個最佳選擇是什么?

我不喜歡header的寬度如何超過滾動條。 動畫跳動不靈。

 $(function(){ var btop = $(".box").offset().top; bwidth = $(".box").innerWidth(); $(".box").on("scroll", function(e){ if($(this).scrollTop() > 50){ $(this).find(".header").css({ "position" : "absolute", "top" : btop, "max-width" : bwidth, }).animate({ "height" :"2em" }) }else{ $(this).find(".header").css({ "position" : "static", "top" : btop, "max-width" : bwidth }).animate({ "height" :"3em" }) } }) }) 
 .box{ margin: 4em auto; height: 12em; width: 20em; background: blue; overflow-y: scroll; /*overflow-x: hidden;*/ /*position: relative;*/ } .header{ background: orange; width: 100%; height: 3em; font-size: 1.3em; } .content{ width: 90%; margin: 0 auto; background: powderblue; height: 12em; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> <div class="box"> <div class="header">This will stick</div> <div class="content">Other content</div> <div class="content">Somemore content</div> </div> 

這只是一個主意,但是在您遇到的情況下,您可以使用簡單的技巧來偽造粘性標頭。

  1. 刪除.box divoverflow-y: scroll屬性。

  2. .header設置一個position: absolute屬性。

  3. 添加一個包含您的.content div的div .content-container ,並將其設置為position: absolute屬性,同時將其設置為overflow-y: scroll

這樣,標題始終位於.box div頂部,並且可以滾動內容。 然后,使用您的JS代碼,您可以在scroll event更改標頭的高度。

 $(document).ready(function(){ $('.content').scroll(function(){ if ($('.content').scrollTop() >= 60){ $('.header').addClass('sticky'); } else { $('.header').removeClass('sticky'); } }); }); 
 .box{ margin: 4em auto; height: 360px; width: 20em; background: blue; position: relative; } .header{ position: absolute; top: 0; background: orange; width: 100%; height: 60px; font-size: 1.3em; z-index: 9999; transition: height 0.3s ease 0s; -webkit-transition: height 0.3s ease 0s; -moz-transition: height 0.3s ease 0s; } .header.sticky{ height: 30px; } .content{ position: absolute; top: 0; width: 100%; height: 300px; padding-top: 60px; background: powderblue; overflow-y: scroll; } .content > div{ height: 500px; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div class="box"> <div class="header">This will stick</div> <div class="content"> <div>Content</div> <div>Somemore content</div> </div> </div> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM