Home  >  Article  >  Web Front-end  >  How to Fix a Fixed Div\'s Horizontal Position During Scrolling?

How to Fix a Fixed Div\'s Horizontal Position During Scrolling?

Linda Hamilton
Linda HamiltonOriginal
2024-11-01 22:28:02503browse

How to Fix a Fixed Div's Horizontal Position During Scrolling?

Horizontal Scrolling of Fixed Position Div

In this query, a user seeks a solution to prevent content clash when a fixed div is horizontally scrolled alongside other content. The initial implementation using jQuery successfully fixes the div vertically, but lacks support for horizontal scrolling.

The proposed solution involves modifying the jQuery code to manipulate the left property of the element:

var leftInit = $(".scroll_fixed").offset().left;
var top = $('.scroll_fixed').offset().top - parseFloat($('.scroll_fixed').css('margin-top').replace(/auto/, 0));


$(window).scroll(function(event) {
    var x = 0 - $(this).scrollLeft();
    var y = $(this).scrollTop();

    // whether that's below the form
    if (y >= top) {
        // if so, ad the fixed class
        $('.scroll_fixed').addClass('fixed');
    } else {
        // otherwise remove it
        $('.scroll_fixed').removeClass('fixed');
    }

    $(".scroll_fixed").offset({
        left: x + leftInit
    });

});

Explanation

  1. leftInit stores the initial left offset of the div.
  2. On scroll, the x value is set as the negative of the current scroll offset, which effectively moves the div along with the horizontal scroll.
  3. leftInit ensures that any left margin on the div is properly considered.

This approach maintains the fixed position of the div while allowing it to scroll horizontally alongside the content, preventing clashes and improving user experience.

The above is the detailed content of How to Fix a Fixed Div\'s Horizontal Position During Scrolling?. 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