복붙노트

[JQUERY] 수직 스크롤을 기반으로 jQuery로 / 제거 클래스를 추가 하시겠습니까?

JQUERY

수직 스크롤을 기반으로 jQuery로 / 제거 클래스를 추가 하시겠습니까?

해결법


  1. 1.

    $(window).scroll(function() {    
        var scroll = $(window).scrollTop();
    
         //>=, not <=
        if (scroll >= 500) {
            //clearHeader, not clearheader - caps H
            $(".clearHeader").addClass("darkHeader");
        }
    }); //missing );
    

    깡깡이

    또한, clearHeader 클래스를 제거하여, 당신은 위치를 제거하고 : 고정; 소자뿐만 아니라 능력으로부터 $ ( ". clearHeader ')을 통해 선택을 다시 선택하는 단계를 포함한다. 그 클래스를 제거하고 목적으로 스타일링을 위해 그 위에 새로운 CSS 클래스를 추가하지 않는 게 좋을 것.

    그리고 당신은 사용자가 스크롤 백업 할 때 클래스 추가 "재설정"하려면 :

    $(window).scroll(function() {    
        var scroll = $(window).scrollTop();
    
        if (scroll >= 500) {
            $(".clearHeader").addClass("darkHeader");
        } else {
            $(".clearHeader").removeClass("darkHeader");
        }
    });
    

    깡깡이

    편집 : 헤더 선택 캐싱 다음 버전 -는 DOM을 스크롤 할 때마다 쿼리하지 않으며 안전하게 제거 / 참조를 잃지 않고 헤더 요소에 대한 클래스를 추가 할 수있는 더 나은 성능을 :

    $(function() {
        //caches a jQuery object containing the header element
        var header = $(".clearHeader");
        $(window).scroll(function() {
            var scroll = $(window).scrollTop();
    
            if (scroll >= 500) {
                header.removeClass('clearHeader').addClass("darkHeader");
            } else {
                header.removeClass("darkHeader").addClass('clearHeader');
            }
        });
    });
    

    깡깡이


  2. 2.당신이 좋아하는 경우에 일부 전환 효과 추가 :

    당신이 좋아하는 경우에 일부 전환 효과 추가 :

    http://jsbin.com/boreme/17/edit?html,css,js

    .clearHeader {
      height:50px;
      background:lightblue;
      position:fixed;
      top:0;
      left:0;
      width:100%;
    
      -webkit-transition: background 2s; /* For Safari 3.1 to 6.0 */
      transition: background 2s;
    }
    
    .clearHeader.darkHeader {
     background:#000;
    }
    

  3. 3.그것의 내 코드

    그것의 내 코드

    jQuery(document).ready(function(e) {
        var WindowHeight = jQuery(window).height();
    
        var load_element = 0;
    
        //position of element
        var scroll_position = jQuery('.product-bottom').offset().top;
    
        var screen_height = jQuery(window).height();
        var activation_offset = 0;
        var max_scroll_height = jQuery('body').height() + screen_height;
    
        var scroll_activation_point = scroll_position - (screen_height * activation_offset);
    
        jQuery(window).on('scroll', function(e) {
    
            var y_scroll_pos = window.pageYOffset;
            var element_in_view = y_scroll_pos > scroll_activation_point;
            var has_reached_bottom_of_page = max_scroll_height <= y_scroll_pos && !element_in_view;
    
            if (element_in_view || has_reached_bottom_of_page) {
                jQuery('.product-bottom').addClass("change");
            } else {
                jQuery('.product-bottom').removeClass("change");
            }
    
        });
    
    });
    

    그 작업 파인


  4. 4.이 값은 구성되어 있습니까? 경우 (스크롤 <= 500) {...이 그것을 500 0에서 일어나고 수단, 그리고 500 이상이다. 원래 포스트에서는 "약간 아래로 사용자가 스크롤 한 후"말했다

    이 값은 구성되어 있습니까? 경우 (스크롤 <= 500) {...이 그것을 500 0에서 일어나고 수단, 그리고 500 이상이다. 원래 포스트에서는 "약간 아래로 사용자가 스크롤 한 후"말했다


  5. 5.유사한 경우에, 나는 인해 성능 문제에 addClass 또는 removeClass를 호출 항상 피하기 위해 원했다. I는 현재의 상태에 따라 두 개의 개별적인 기능으로 스크롤 핸들러 함수를 나누어 사용했다. 나는 또한이 문서에 따라 디 바운스 기능을 추가 : https://developers.google.com/web/fundamentals/performance/rendering/debounce-your-input-handlers

    유사한 경우에, 나는 인해 성능 문제에 addClass 또는 removeClass를 호출 항상 피하기 위해 원했다. I는 현재의 상태에 따라 두 개의 개별적인 기능으로 스크롤 핸들러 함수를 나누어 사용했다. 나는 또한이 문서에 따라 디 바운스 기능을 추가 : https://developers.google.com/web/fundamentals/performance/rendering/debounce-your-input-handlers

            var $header = jQuery( ".clearHeader" );         
            var appScroll = appScrollForward;
            var appScrollPosition = 0;
            var scheduledAnimationFrame = false;
    
            function appScrollReverse() {
                scheduledAnimationFrame = false;
                if ( appScrollPosition > 500 )
                    return;
                $header.removeClass( "darkHeader" );
                appScroll = appScrollForward;
            }
    
            function appScrollForward() {
                scheduledAnimationFrame = false;
                if ( appScrollPosition < 500 )
                    return;
                $header.addClass( "darkHeader" );
                appScroll = appScrollReverse;
            }
    
            function appScrollHandler() {
                appScrollPosition = window.pageYOffset;
                if ( scheduledAnimationFrame )
                    return;
                scheduledAnimationFrame = true;
                requestAnimationFrame( appScroll );
            }
    
            jQuery( window ).scroll( appScrollHandler );
    

    어쩌면 사람이 도움을 찾습니다.


  6. 6.여기에 스크롤 동안 수업을 처리 순수 자바 스크립트 예제입니다.

    여기에 스크롤 동안 수업을 처리 순수 자바 스크립트 예제입니다.

    당신은 아마 스로틀 처리 스크롤 이벤트에 더 많은 그래서 핸들러 논리는 lodash lib 디렉토리의 경우 스로틀에, 더 복잡한수록 유용 할 것입니다.

    당신이 스파를하고 있다면, 그들은 필요하지 않을 일단 당신이 때 removeEventListener 분명 이벤트 리스너에 필요한 것을 명심 (예 : 뷰에 대한) (파괴, 또는 같은 구성 요소의들의 OnDestroy 라이프 사이클 후크 동안, 어쩌면 useEffect 후크의 기능을 반환 에 대한) 반응한다.

    CONST = document.getElementById를 메뉴 바 ( '메뉴 바') // OnScroll 이벤트 핸들러 CONST onScroll = () => { // 가져 오기 스크롤 값 CONST 스크롤 = document.documentElement.scrollTop // 만약 스크롤 값이 0보다 - 클래스 추가 경우 (스크롤> 0) { navbar.classList.add ( "스크롤"); } 다른 { navbar.classList.remove ( "스크롤") } } // 선택 사항 - 조절 onScroll 핸들러 lodash와이 100ms에서 CONST throttledOnScroll = _.throttle (onScroll, 100, {}) // 사용 중 onScroll 또는 throttledOnScroll window.addEventListener ( '스크롤'onScroll) #navbar { 위치 : 고정; 최고 : 0; 왼쪽 : 0; 오른쪽 : 0; 폭 : 100 %; 높이 : 60 픽셀; 배경 색상 : # 89d0f7; 상자 그림자 : 0 픽셀 5px 0 픽셀 RGBA (0, 0, 0, 0); 전환 : 박스 그림자 500ms 이내; } # navbar.scrolled { 상자 그림자 : 0 픽셀 5px 10px RGBA (0, 0, 0, 0.25); } #content { 높이 : 3000px; 여백 - 상단 : 60 픽셀; } <스크립트 SRC = "https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"> <헤더 ID = "메뉴 바">


  7. 7.안드로이드 모바일 $ (창) .scroll (함수 ()와 $ (문서) .scroll (함수 ()의 경우 또는 작동하지 않을 수 있습니다. 그래서 대신 다음을 사용할 수 있습니다.

    안드로이드 모바일 $ (창) .scroll (함수 ()와 $ (문서) .scroll (함수 ()의 경우 또는 작동하지 않을 수 있습니다. 그래서 대신 다음을 사용할 수 있습니다.

    jQuery(document.body).scroll(function() {
            var scroll = jQuery(document.body).scrollTop();
    
            if (scroll >= 300) {
                //alert();
                header.addClass("sticky");
            } else {
                header.removeClass('sticky');
            }
        });
    

    이 코드는 나를 위해 일했다. 그것은 당신을 도울 것입니다 바랍니다.

  8. from https://stackoverflow.com/questions/12558311/add-remove-class-with-jquery-based-on-vertical-scroll by cc-by-sa and MIT license