触发事件,当用户滚动到特定元素 - 与jQuery触发事件,当用户滚动到特定元素 - 与jQuery

2019-05-09 00:03发布

我有一个H1是远了一个网页..

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

我想触发警报当用户滚动到H1,还是有它在它的浏览器视图。

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

我该怎么做呢?

Answer 1:

你可以计算出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!');
   }
});

勾选此演示小提琴


更新演示小提琴无警报-而不是淡入()元素


检查更新的代码,如果该元素是视内部或没有。 因此,这部作品无论您是向上或向下滚动添加一些规则if语句:

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

演示小提琴



Answer 2:

结合这个问题,从最佳答案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
    }
});

UPDATE

我已经改进了代码,这样,当元素是半山腰的屏幕,而不是在最顶端就会触发。 如果用户点击屏幕下方和功能还没有启动它还将触发代码。

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


Answer 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/



Answer 4:

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



Answer 5:

这应该是你所需要的。

使用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



Answer 6:

您可以使用jQuery插件与inview这样的事件:

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

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



Answer 7:

只是一个快速修改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;
}


Answer 8:

如果您是基于滚动位置做了很多的功能,魔法卷轴( http://scrollmagic.io/ )完全是建立用于此目的。

它可以很容易地根据当用户滚动时达到某些元素上触发JS。 它也与GSAP动画引擎(集成https://greensock.com/ ),这对于视差滚动网站是伟大的



Answer 9:

您可以使用此对所有设备,

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


Answer 10:

一个成功的滚动后,消防滚动一次

接受的答案为我工作(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();
            }

        });

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



Answer 11:

我使用相同的代码做,所有的时间,所以添加了一个简单的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的一半需要提醒。



文章来源: Trigger event when user scroll to specific element - with jQuery