Home  >  Article  >  Web Front-end  >  How to Make a Fixed-Position Div Scroll Horizontally with Content Using jQuery?

How to Make a Fixed-Position Div Scroll Horizontally with Content Using jQuery?

DDD
DDDOriginal
2024-10-28 04:35:30144browse

How to Make a Fixed-Position Div Scroll Horizontally with Content Using jQuery?

How to Scroll a Fixed Position Div Horizontally with Content Using jQuery

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:

CSS

<code class="css">.scroll_fixed {
    position: absolute;
    top: 210px;
}

.scroll_fixed.fixed {
    position: fixed;
    top: 0;
}</code>

jQuery

<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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn