복붙노트

[JQUERY] 트리거 이벤트 때 특정 요소에 대한 사용자 스크롤 - jQuery로

JQUERY

트리거 이벤트 때 특정 요소에 대한 사용자 스크롤 - jQuery로

해결법


  1. 1.당신은 요소의 오프셋 (offset)를 계산 한 후 스크롤 값 등으로 있음을 비교할 수 있습니다

    당신은 요소의 오프셋 (offset)를 계산 한 후 스크롤 값 등으로 있음을 비교할 수 있습니다

    $(window).scroll(function() {
       var hT = $('#scroll-to').offset().top,
           hH = $('#scroll-to').outerHeight(),
           wH = $(window).height(),
           wS = $(this).scrollTop();
       if (wS > (hT+hH-wH)){
           console.log('H1 on the view!');
       }
    });
    

    이 데모 바이올린을 확인

    대신 FadeIn () 요소 - 데모 바이올린 어떤 경고 업데이트

    요소가 뷰포트 내부 또는없는 경우 업데이트 된 코드를 확인합니다. 따라서 이것은 당신이 스크롤하거나 if 문에 일부 규칙을 추가 아래 여부를 작동 :

       if (wS > (hT+hH-wH) && (hT > wS) && (wS+wH > hT+hH)){
           //Do something
       }
    

    데모 바이올린


  2. 2.jQuery를 트리거 동작에서 최상의 답이 질문에 결합 할 때 페이지의 특정 부분을지나 사용자가 스크롤

    jQuery를 트리거 동작에서 최상의 답이 질문에 결합 할 때 페이지의 특정 부분을지나 사용자가 스크롤

    var element_position = $('#scroll-to').offset().top;
    
    $(window).on('scroll', function() {
        var y_scroll_pos = window.pageYOffset;
        var scroll_pos_test = element_position;
    
        if(y_scroll_pos > scroll_pos_test) {
            //do stuff
        }
    });
    

    최신 정보

    나는 요소가 화면 위로보다는 매우 상단에 절반 방법입니다 때 트리거되도록 코드를 개선했습니다. 사용자가 화면의 하단에 도달하고, 기능이 아직 발사되지 않은 경우에도 코드를 트리거합니다.

    var element_position = $('#scroll-to').offset().top;
    var screen_height = $(window).height();
    var activation_offset = 0.5;//determines how far up the the page the element needs to be before triggering the function
    var activation_point = element_position - (screen_height * activation_offset);
    var max_scroll_height = $('body').height() - screen_height - 5;//-5 for a little bit of buffer
    
    //Does something when user scrolls to it OR
    //Does it when user has reached the bottom of the page and hasn't triggered the function yet
    $(window).on('scroll', function() {
        var y_scroll_pos = window.pageYOffset;
    
        var element_in_view = y_scroll_pos > 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) {
            //Do something
        }
    });
    

  3. 3.나는 당신의 가장 좋은 건 바로 그 일을 기존 라이브러리를 활용할 수있을 거라고 생각 :

    나는 당신의 가장 좋은 건 바로 그 일을 기존 라이브러리를 활용할 수있을 거라고 생각 :

    http://imakewebthings.com/jquery-waypoints/

    당신은 당신의 요소는 뷰포트의 상단을 칠 때 해고됩니다 요소에 리스너를 추가 할 수 있습니다 :

    $('#scroll-to').waypoint(function() {
     alert('you have scrolled to the h1!');
    });
    

    사용 그것의 놀라운 데모 :

    http://tympanus.net/codrops/2013/07/16/on-scroll-header-effects/


  4. 4.원한다면 InView 라이브러리는 이벤트를 트리거 및 JQuery와 1.8 이상에서 잘 작동합니다! https://github.com/protonet/jquery.inview

    원한다면 InView 라이브러리는 이벤트를 트리거 및 JQuery와 1.8 이상에서 잘 작동합니다! https://github.com/protonet/jquery.inview

    $('div').on('inview', function (event, visible) {
      if (visible == true) {
        // element is now visible in the viewport
      } else {
        // element has gone out of viewport
      }
    });
    

    https://remysharp.com/2009/01/26/element-in-view-event-plugin을이 읽기


  5. 5.이 같은 원한다면 InView 이벤트와 플러그인 jQuery를 사용할 수 있습니다 :

    이 같은 원한다면 InView 이벤트와 플러그인 jQuery를 사용할 수 있습니다 :

    jQuery('.your-class-here').one('inview', function (event, visible) {
        if (visible == true) {
          //Enjoy !
        }
    });
    

    링크 : https://remysharp.com/2009/01/26/element-in-view-event-plugin


  6. 6.당신은 모든 장치에 대해이 사용할 수

    당신은 모든 장치에 대해이 사용할 수

    $(document).on('scroll', function() {
        if( $(this).scrollTop() >= $('#target_element').position().top ){
            do_something();
        }
    });
    

  7. 7.단지 성공적으로 스크롤 한 후 한 번 화재 스크롤

    단지 성공적으로 스크롤 한 후 한 번 화재 스크롤

    허용 대답은 나 (90 %)에 근무하지만 실제로는 한 번만 불에 그것을 조금 조정할했다.

    $(window).on('scroll',function() {
                var hT = $('#comment-box-section').offset().top,
                    hH = $('#comment-box-section').outerHeight(),
                    wH = $(window).height(),
                    wS = $(this).scrollTop();
    
                if (wS > ((hT+hH-wH)-500)){
                    console.log('comment box section arrived! eh');
                    // After Stuff
                    $(window).off('scroll');
                    doStuff();
                }
    
            });
    

  8. 8.이것은 당신이 필요로해야한다.

    이것은 당신이 필요로해야한다.

    자바 스크립트 :

    $(window).scroll(function() {
        var hT = $('#circle').offset().top,
            hH = $('#circle').outerHeight(),
            wH = $(window).height(),
            wS = $(this).scrollTop();
        console.log((hT - wH), wS);
        if (wS > (hT + hH - wH)) {
            $('.count').each(function() {
                $(this).prop('Counter', 0).animate({
                    Counter: $(this).text()
                }, {
                    duration: 900,
                    easing: 'swing',
                    step: function(now) {
                        $(this).text(Math.ceil(now));
                    }
                });
            }); {
                $('.count').removeClass('count').addClass('counted');
            };
        }
    });
    

    CSS :

    #circle
    {
        width: 100px;
        height: 100px;
        background: blue;
        -moz-border-radius: 50px;
        -webkit-border-radius: 50px;
        border-radius: 50px;
        float:left;
        margin:5px;
    }
    .count, .counted
    {
      line-height: 100px;
      color:white;
      margin-left:30px;
      font-size:25px;
    }
    #talkbubble {
       width: 120px;
       height: 80px;
       background: green;
       position: relative;
       -moz-border-radius:    10px;
       -webkit-border-radius: 10px;
       border-radius:         10px;
       float:left;
       margin:20px;
    }
    #talkbubble:before {
       content:"";
       position: absolute;
       right: 100%;
       top: 15px;
       width: 0;
       height: 0;
       border-top: 13px solid transparent;
       border-right: 20px solid green;
       border-bottom: 13px solid transparent;
    }
    

    HTML :

    <div id="talkbubble"><span class="count">145</span></div>
    <div style="clear:both"></div>
    <div id="talkbubble"><span class="count">145</span></div>
    <div style="clear:both"></div>
    <div id="circle"><span class="count">1234</span></div>
    

    이 bootply을 확인합니다 : http://www.bootply.com/atin_agarwal2/cJBywxX5Qp


  9. 9.당신이 스크롤 위치에 따라 많은 기능을 수행하는 경우, 스크롤 마법 (http://scrollmagic.io/)이 목적을 위해 완전히 내장되어 있습니다.

    당신이 스크롤 위치에 따라 많은 기능을 수행하는 경우, 스크롤 마법 (http://scrollmagic.io/)이 목적을 위해 완전히 내장되어 있습니다.

    이 스크롤 될 때, 사용자가 특정 요소에 도달 할 때 트리거에 기초하여 용이 JS를 만든다. 또한 시차 스크롤 웹 사이트에 대한 좋은입니다 GSAP 애니메이션 엔진 (https://greensock.com/)와 통합


  10. 10.때때로 장치의 뷰포트의 경계를 넘어 확장 할 수있는 요소와 사람의 거래에 대한 DaniP의 대답에 그냥 빨리 수정.

    때때로 장치의 뷰포트의 경계를 넘어 확장 할 수있는 요소와 사람의 거래에 대한 DaniP의 대답에 그냥 빨리 수정.

    단지 약간의 조건을 추가 -이 상반신을 완전히 뷰포트를 작성하고있다 일단 뷰포트보다 큰 요소의 경우, 요소가 공개됩니다.

    function elementInView(el) {
      // The vertical distance between the top of the page and the top of the element.
      var elementOffset = $(el).offset().top;
      // The height of the element, including padding and borders.
      var elementOuterHeight = $(el).outerHeight();
      // Height of the window without margins, padding, borders.
      var windowHeight = $(window).height();
      // The vertical distance between the top of the page and the top of the viewport.
      var scrollOffset = $(this).scrollTop();
    
      if (elementOuterHeight < windowHeight) {
        // Element is smaller than viewport.
        if (scrollOffset > (elementOffset + elementOuterHeight - windowHeight)) {
          // Element is completely inside viewport, reveal the element!
          return true;
        }
      } else {
        // Element is larger than the viewport, handle visibility differently.
        // Consider it visible as soon as it's top half has filled the viewport.
        if (scrollOffset > elementOffset) {
          // The top of the viewport has touched the top of the element, reveal the element!
          return true;
        }
      }
      return false;
    }
    

  11. 11.교차로 관찰자는 정말 좋은 일을 외부 라이브러리없이, IMO 가장 좋은 일이 될 수 있습니다.

    교차로 관찰자는 정말 좋은 일을 외부 라이브러리없이, IMO 가장 좋은 일이 될 수 있습니다.

    const options = {
                root: null,
                threshold: 0.25, // 0 - 1 this work as a trigger. 
                rootMargin: '150px'
            };
    
            const target = document.querySelector('h1#scroll-to');
            const observer = new IntersectionObserver(
               entries => { // each entry checks if the element is the view or not and if yes trigger the function accordingly
                entries.forEach(() => {
                    alert('you have scrolled to the h1!')
                });
            }, options);
            observer.observe(target);
    

  12. 12.나는 모든 시간, 그래서 그 일을 플러그인 간단한 jQuery를 추가 한 일을 동일한 코드를 사용합니다. 480 바이트, 빠른. 만 바인딩 요소는 런타임 분석했다.

    나는 모든 시간, 그래서 그 일을 플러그인 간단한 jQuery를 추가 한 일을 동일한 코드를 사용합니다. 480 바이트, 빠른. 만 바인딩 요소는 런타임 분석했다.

    https://www.npmjs.com/package/jquery-on-scrolled-to

    그것은 될 것입니다 $ ( '# 스크롤에'). onScrolledTo (0, 함수 () { 경고 ( '당신은 H1으로 스크롤 한!'); });

    H1의 절반이 도시 된 때 또는 경보 0.5 0 대신 필요하다면 사용.

  13. from https://stackoverflow.com/questions/21561480/trigger-event-when-user-scroll-to-specific-element-with-jquery by cc-by-sa and MIT license