To ensure a fixed div scrolls horizontally with the content, a combination of CSS and jQuery code is necessary. Here's how to implement it:
<code class="css">.scroll_fixed { position: absolute; top: 210px; } .scroll_fixed.fixed { position: fixed; top: 0; }</code>
<code class="javascript">// Retrieve the initial left offset var leftInit = $(".scroll_fixed").offset().left; // Get the top offset of the div var top = $('.scroll_fixed').offset().top - parseFloat($('.scroll_fixed').css('margin-top').replace(/auto/, 0)); $(window).scroll(function(event) { // Calculate the horizontal scroll position var x = 0 - $(this).scrollLeft(); // Calculate the vertical scroll position var y = $(this).scrollTop(); // Position the div based on scroll // Horizontally: Left margin of the initial position minus the horizontal scroll position // Vertically: Top margin of the initial position minus the vertical scroll position if (y >= top) { // Display the div at the top of the viewport $('.scroll_fixed').addClass('fixed'); } else { // Remove the 'fixed' class from the div $('.scroll_fixed').removeClass('fixed'); } $(".scroll_fixed").offset({ left: x + leftInit, top: y }); });</code>
This code manages the horizontal scrolling by adjusting the left property of the div, ensuring that it remains synchronized with the content. The leftInit variable incorporates possible left margins to enhance the function's accuracy.
The above is the detailed content of How to Make a Fixed-Position Div Scroll Horizontally with Content Using jQuery?. For more information, please follow other related articles on the PHP Chinese website!