[英]Positioning a div to fixed on scroll to parent div
我有一個 div scroll-content
,其中包含另一個 div fixme
,我只想在scroll-content
div 位於屏幕頂部時對其進行修復。 如果用戶滾動經過scroll-content
div,則fixme
應該消失。 我正在使用下面的代碼,但它似乎不起作用:
var fixmeTop = $('.fixme').offset().top; $(window).scroll(function() { var currentScroll = $(window).scrollTop(); if (currentScroll >= fixmeTop) { $('.fixme').css({ position: 'fixed', top: '50%', left: '50%', display: 'block' }); } else { $('.fixme').css({ display: 'none' }); } });
body { height: 3000px; }.content { height: 500px; background: white; }.scroll-content { background: black; height: 1000px; }.fixme { background: green; color: white; text-align: center; width: 100px; height: 100px; display: none; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script> <div class="content"></div> <div class="scroll-content"> <div class="fixme">Scroll here</div> </div>
這是一個示例,它使用 position 粘性將.fixme
元素保留在.scroll-content
元素內。 由於 jQuery 用fixed
覆蓋了position
屬性,因此在您自己的嘗試之前它可能不起作用。
我希望這是想要的效果。
否則請告訴我們,以便我們幫助您找出另一種解決方案。
body { height: 3000px; }.content { height: 500px; background: white; }.scroll-content { position: relative; background: black; height: 1000px; }.fixme { position: sticky; top: calc(50% - 50px); left: 50%; background: green; color: white; text-align: center; width: 100px; height: 100px; transform: translate(-50%, 0%); }
<div class="content"></div> <div class="scroll-content"> <div class="fixme">Scroll here</div> </div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.