Maison > Article > interface Web > Comment réparer un div en haut de la fenêtre lors du défilement avec 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' }); } });
Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!