>  기사  >  웹 프론트엔드  >  jQuery를 사용하여 고정 위치 Div를 콘텐츠와 함께 가로로 스크롤하는 방법은 무엇입니까?

jQuery를 사용하여 고정 위치 Div를 콘텐츠와 함께 가로로 스크롤하는 방법은 무엇입니까?

DDD
DDD원래의
2024-10-28 04:35:30144검색

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

jQuery를 사용하여 고정 위치 Div를 콘텐츠와 함께 가로로 스크롤하는 방법

고정 div가 콘텐츠와 함께 가로로 스크롤되도록 하려면 CSS와 jQuery 코드의 조합이 필요합니다. . 구현 방법은 다음과 같습니다.

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>

이 코드는 div의 왼쪽 속성을 조정하여 가로 스크롤을 관리합니다. 콘텐츠와 동기화된 상태를 유지합니다. leftInit 변수는 가능한 왼쪽 여백을 통합하여 함수의 정확성을 향상시킵니다.

위 내용은 jQuery를 사용하여 고정 위치 Div를 콘텐츠와 함께 가로로 스크롤하는 방법은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.