繁体   English   中英

内容的固定位置,直到父div结束

[英]Fixed position of content until parent div ends

我有一段代码,当y-scoll超过765px时得到修复。 问题在于,即使在其父级之外,此内容也将被修复。 这是一个示例: https : //jsfiddle.net/rwbsua3v/

如您所见,在继续滚动时,绿色框中的内容将固定,并且在滚动时将覆盖蓝色框。

如果我知道红色/绿色和蓝色框的确切高度,我可以解决此问题,但问题是它们可以任意长度。 如何在不影响y-scroll偏移量和css top:87px的情况下,固定绿色框中的内容,直到它碰到父对象的底部(绿色框)?

这是我的代码:

 window.onscroll = function() { myFunction() }; var floating1 = document.getElementById("floating1"); var yOffset = 765; function myFunction() { if (window.pageYOffset > yOffset) { floating1.classList.add("sticky"); } else { floating1.classList.remove("sticky"); } } 
 table { width: 100%; min-height: 2000px; } table tr td { vertical-align: top; } .sticky { position: fixed!important; top: 87px; } 
 <table> <tr> <td style="background: red; width: 200px;"> ... </td> <td style="background: green; width: 200px;"> <div id="floating1"> Floating content </div> </td> </tr> </table> <div style="height: 1500px; background: blue;"> ... </div> 

使用position: sticky ,可将元素固定到位,直到遇到容器的边缘:

 window.onscroll = function() { myFunction() }; var floating1 = document.getElementById("floating1"); var yOffset = 765; function myFunction() { if (window.pageYOffset > yOffset) { floating1.classList.add("sticky"); } else { floating1.classList.remove("sticky"); } } 
 table { width: 100%; min-height: 2000px; } table tr td { vertical-align: top; } .sticky { position: sticky; top: 87px; } 
 <table> <tr> <td style="background: red; width: 200px;"> ... </td> <td style="background: green; width: 200px;"> <div id="floating1"> Floating content </div> </td> </tr> </table> <div style="height: 1500px; background: blue;"> ... </div> 

这是一个有效的小提琴: https : //jsfiddle.net/17rn4qtw/2/

  1. 我在浮动内容的父级中添加了id="parent" ,并使用Javascript来获取其高度。
  2. 我在函数中添加了第二个if子句,该子句仅在页面偏移量小于div内容高度时才修复浮动内容。

我还从父级的高度中减去了顶部像素,因此浮动内容在父级外时消失了,而不仅仅是父级在窗口视图外时消失了。

为您的div添加一个green的类,并检查何时结束。

 window.onscroll = function() {myFunction()}; var floating1 = document.getElementById("floating1"); var yOffset = 765; function myFunction() { if (window.pageYOffset > yOffset && window.pageYOffset < $('.green').height()) { floating1.classList.add("sticky"); } else if (window.pageYOffset > $('.green').height()) { floating1.classList.remove("sticky"); } else { floating1.classList.remove("sticky"); } } 
 table { width: 100%; min-height: 2000px; } table tr td { vertical-align: top; } .sticky { position: fixed!important; top: 87px; } 
 <table> <tr> <td style="background: red; width: 200px;"> ... </td> <td style="background: green; width: 200px;" class="green"> <div id="floating1"> Floating content </div> </td> </tr> </table> <div style="height: 1500px; background: blue;"> ... </div> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> 

https://jsfiddle.net/djkog8ft/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM