繁体   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