Rumah > Artikel > hujung hadapan web > Bagaimanakah Saya Membetulkan Div ke Bahagian Atas Viewport pada Tatal dengan CSS?
Fixing a Div on Scroll with CSS
Your question pertains to making a div remain fixed after scrolling to it. As you mentioned, simply applying position: fixed to the div causes it to appear before it should on the page.
Fortunately, advancements in CSS now allow for this functionality:
div { position: sticky; top: 0; }
The sticky position property ensures that the div remains fixed once it reaches the top of the viewport, similar to how the second ad on 9gag behaves.
jQuery Alternative
For compatibility with older browsers, here's the original jQuery approach:
$(window).scroll(function () { var scrollTop = $(window).scrollTop(); var divOffset = $('.fixme').offset().top; if (scrollTop >= divOffset) { $('.fixme').css({ position: 'fixed', top: '0', left: '0' }); } else { $('.fixme').css({ position: 'static' }); } });
Atas ialah kandungan terperinci Bagaimanakah Saya Membetulkan Div ke Bahagian Atas Viewport pada Tatal dengan CSS?. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!