用户滚动到特定元素时触发事件 - 使用jQuery

时间:2014-02-04 19:21:40

标签: javascript jquery html scroll scrollto

我有一个远远低于页面的h1 ..

<h1 id="scroll-to">TRIGGER EVENT WHEN SCROLLED TO.</h1>

我希望在用户滚动到h1时触发警报,或者在浏览器的视图中显示警告。

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

我该怎么做?

13 个答案:

答案 0 :(得分:115)

您可以计算元素的offset,然后将其与scroll值进行比较,如:

$(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!');
   }
});

选中 Demo Fiddle


更新Demo Fiddle无警报 - 而不是FadeIn()元素


更新了代码以检查元素是否在视口内。因此,无论是向上还是向下滚动,都会向if语句添加一些规则,这是有效的:

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

<强> Demo Fiddle

答案 1 :(得分:20)

将此问题与jQuery trigger action when a user scrolls past a certain part of the page

的最佳答案相结合
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
    }
});

答案 2 :(得分:7)

我认为你最好的办法是利用一个现有的库来做这件事:

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/

答案 3 :(得分:5)

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

答案 4 :(得分:2)

您可以将jQuery pluginhh:mm事件一起使用,如下所示:

inview

链接:https://remysharp.com/2009/01/26/element-in-view-event-plugin

答案 5 :(得分:2)

这应该是你需要的。

使用Javascript:

$(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

答案 6 :(得分:2)

Intersection Observer可能是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);

答案 7 :(得分:1)

只需快速修改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;
}

答案 8 :(得分:1)

您可以将其用于所有设备,

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

答案 9 :(得分:1)

如果您正在寻找 javascript 版本。您可以在 scroll 事件侦听器上调用此方法。

  showScrollTop = () =>{
    const currentScrollPosition = window.pageYOffset; 
    let elementID = 'service-selector'
    const elementOffsetTop = document.getElementById(elementID).offsetTop

    if ( currentScrollPosition > elementOffsetTop){
     // place your logic here 
    } else {
      // place your logic here 
    }
  }

  window.addEventListener('scroll', showScrollTop)

答案 10 :(得分:0)

If you are doing a lot of functionality based on scroll position, Scroll magic (http://scrollmagic.io/) is built entirely for this purpose.

It makes it easy to trigger JS based on when the user reaches certain elements when scrolling. It also integrates with the GSAP animation engine (https://greensock.com/) which is great for parallax scrolling websites

答案 11 :(得分:0)

成功滚动后只能滚动一次

可接受的答案对我有用(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();
            }

        });
  

注意:成功滚动是指用户滚动到我的元素或   换句话说,当我的元素在视野中时。

答案 12 :(得分:-1)

我一直使用相同的代码,因此添加了一个简单的jquery插件。 480字节长,而且速度很快。在运行时仅分析绑定的元素。

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

这将是 $('#scroll-to').onScrolledTo(0, function() { alert('you have scrolled to the h1!'); });

或者如果需要在显示一半的h1时发出警报,则使用0.5而不是0。