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

Javascript 当用户滚动到特定元素时触发事件-使用jQuery,javascript,jquery,html,scroll,scrollto,Javascript,Jquery,Html,Scroll,Scrollto,我有一个h1在一页下面 <h1 id="scroll-to">TRIGGER EVENT WHEN SCROLLED TO.</h1> 如何做到这一点?我认为您最好的选择是利用现有的库来实现这一点: 可以将侦听器添加到元素中,当元素到达视口顶部时,这些侦听器将触发: $('#scroll-to').waypoint(function() { alert('you have scrolled to the h1!'); }); 对于正在使用的it的惊人演示: 您可以

我有一个h1在一页下面

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

如何做到这一点?

我认为您最好的选择是利用现有的库来实现这一点:

可以将侦听器添加到元素中,当元素到达视口顶部时,这些侦听器将触发:

$('#scroll-to').waypoint(function() {
 alert('you have scrolled to the h1!');
});
对于正在使用的it的惊人演示:


您可以计算元素的
偏移量
,然后将其与
滚动
值进行比较,如:

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

将此问题与来自

更新

我已经改进了代码,这样当元素在屏幕的一半位置而不是最顶端时,它就会触发。如果用户点击屏幕底部并且函数还没有启动,它也会触发代码

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
    }
});
var element_position=$('#滚动到'.offset().top;
var screen_height=$(window.height();
var激活_偏移=0.5//确定在触发函数之前元素需要在页面上方多远
var激活点=元件位置-(屏幕高度*激活偏移);
var max_scroll_height=$('body').height()-屏幕高度-5//-5来点缓冲
//当用户滚动到它或
//当用户到达页面底部并且还没有触发该功能时,是否执行此操作
$(窗口).on('scroll',function(){
变量y_scroll_pos=window.pageYOffset;
视图中的变量元素=y滚动位置>激活点;

var已到达查看库触发事件中页面=max\u scroll\u height的底部,并且与jquery 1.8及更高版本配合良好!


阅读此

如果您正在基于滚动位置执行许多功能,则scroll magic()完全是为此而构建的

当用户在滚动时达到某些元素时,它可以很容易地触发JS。它还与GSAP动画引擎()集成,这对于视差滚动网站是非常好的

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

链接:

这应该是您所需要的

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:

HTML:

145
145
1234
检查此引导程序:

这只是对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;
}
只添加了一个轻微的条件-对于大于视口的元素,一旦元素的上半部分完全填充视口,就会显示该元素

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;
}
功能元素视图(el){
//页面顶部和元素顶部之间的垂直距离。
var elementOffset=$(el).offset().top;
//元素的高度,包括填充和边框。
var elementOuterHeight=$(el.outerHeight();
//不带边距、填充、边框的窗口高度。
var windowHeight=$(window.height();
//页面顶部和视口顶部之间的垂直距离。
var scrollOffset=$(this.scrollTop();
if(元素外部高度<窗口高度){
//元素小于视口。
如果(scrollOffset>(elementOffset+elementOuterHeight-窗口高度)){
//元素完全在视口内,显示元素!
返回true;
}
}否则{
//元素大于视口,则以不同方式处理可见性。
//只要它的上半部分已经填满了视口,就可以看到它。
如果(滚动偏移>元素偏移){
//视口的顶部已经接触到元素的顶部,显示元素!
返回true;
}
}
返回false;
}

您可以将其用于所有设备

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

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

会的

$(“#滚动到”).onScrolledTo(0,函数(){
警报('您已滚动到h1!');
});

如果需要在显示一半的h1时发出警报,请使用0.5而不是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');
        // This detaches the scroll so doStuff() won't run more than once
        $(window).off('scroll');
        doStuff();
    }
});

在我看来,交叉点观察者是最好的东西,没有任何外部库,它的工作真的很好

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

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

  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)

请解除绑定!有没有像jQuery Waypoint这样的函数包库可以实现这一点?谢谢@DaniP.Cool snippet!@ClosDesign您可以使用
.off()
解除绑定事件@DaniP我刚刚做了,谢谢!谢谢您的回答,帮了我很多忙:)我已经试过了。它只会在你滚动过元素后触发。还有其他解决方案吗?这个解决方案可以很好地获取建议,我已经在生产中使用过。参考博客:我建议使用不太神秘的变量名,即使accepted answer使用它们。
$(document).on('scroll', function() {
    if( $(this).scrollTop() >= $('#target_element').position().top ){
        do_something();
    }
});
$(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');
        // This detaches the scroll so doStuff() won't run more than once
        $(window).off('scroll');
        doStuff();
    }
});
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);
  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)