When creating a header that remains visible despite scrolling, it's possible to implement this behavior using CSS and HTML alone without the need for jQuery.
Introduce a sticky header class:
<code class="css">.sticky-header { width: 700px; height: 50px; background: orange; position: fixed; }</code>
In your HTML, add a div with the "sticky" class:
<code class="html"><div class="sticky"></div></code>
For precise control over the header's fixation, JavaScript is necessary for scroll events:
<code class="javascript">$(window).scroll(function() { var sticky = $('.sticky'), scroll = $(window).scrollTop(); if (scroll >= 100) { sticky.addClass('fixed'); } else { sticky.removeClass('fixed'); } });</code>
To determine the fixation point based on the sticky element's position on the screen, use offset().top:
<code class="javascript">var stickyOffset = $('.sticky').offset().top; $(window).scroll(function() { var scroll = $(window).scrollTop(); if (scroll >= stickyOffset) { sticky.addClass('fixed'); } else { sticky.removeClass('fixed'); } });</code>
The above is the detailed content of How to Create a Sticky Header with CSS and JavaScript Without jQuery?. For more information, please follow other related articles on the PHP Chinese website!