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


83

我的h1不在页面上。

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

我想在用户滚动到h1或在浏览器视图中触发警报时触发。

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

我该怎么做呢?

Answers:


149

您可以计算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无提示-而是将FadeIn()元素


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

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

演示小提琴


14
请对此进行反跳!
Frambot

1
有没有像jQuery Waypoint这样的函数来执行此操作的包库?
Karl Coelho 2014年

1
谢谢@DaniP。很酷的摘要!
Anahit DEV 2016年

2
@ClosDesign可用于.off()解除绑定事件jsfiddle.net/n4pdx/543
DaniP

1
@DaniP我刚刚做了,谢谢!感谢您的回答,这对我有很大帮助:)
Paolo

30

当用户滚动到页面的特定部分时,将此问题与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
    }
});

9

我认为您最好的选择是利用可完成此任务的现有库:

http://imakewebthings.com/waypoints/

您可以向元素添加侦听器,当元素到达视口顶部时,监听器将触发:

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

有关正在使用的惊人演示:

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


1
我已经尝试过了。仅在滚动PAST元素后才触发。还有其他解决方案吗?
Karl Coelho 2014年

此解决方案很好地用于获取建议,我已经在生产中使用了它。请参阅博客:liyao13.wordpress.com/2017/05/11/...
瑶里


4

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

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

4

成功滚动后仅触发一次滚动

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

        });

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



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>

检查此启动程序:http : //www.bootply.com/atin_agarwal2/cJBywxX5Qp


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);


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;
}

我建议使用较少的神秘变量名,即使已接受的答案使用了它们。
weirdan

0

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

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

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

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

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.