Heim  >  Artikel  >  Web-Frontend  >  Wie erstelle ich mit jQuery einen horizontalen Div-Bildlauf mit fester Position und Inhalt?

Wie erstelle ich mit jQuery einen horizontalen Div-Bildlauf mit fester Position und Inhalt?

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

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

So scrollen Sie mit jQuery ein Div mit fester Position horizontal mit Inhalt

Um sicherzustellen, dass ein Div mit fester Position horizontal mit dem Inhalt scrollt, ist eine Kombination aus CSS- und jQuery-Code erforderlich . So implementieren Sie es:

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>

Dieser Code verwaltet das horizontale Scrollen, indem er die left-Eigenschaft des div anpasst und so sicherstellt, dass es funktioniert bleibt mit dem Inhalt synchronisiert. Die Variable leftInit berücksichtigt mögliche linke Ränder, um die Genauigkeit der Funktion zu verbessern.

Das obige ist der detaillierte Inhalt vonWie erstelle ich mit jQuery einen horizontalen Div-Bildlauf mit fester Position und Inhalt?. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn