当用户滚动到特定元素时触发事件 - 使用 jQuery [英] Trigger event when user scroll to specific element - with jQuery

查看:46
本文介绍了当用户滚动到特定元素时触发事件 - 使用 jQuery的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个位于页面下方的 h1..

I have an h1 that is far down a page..

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

并且我想在用户滚动到 h1 或将其显示在浏览器视图中时触发警报.

and I want to trigger an alert when the user scrolls to the h1, or has it in it's browser's view.

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

我该怎么做?

推荐答案

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

You can calculate the offset of the element and then compare that with the scroll value like:

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

检查这个演示小提琴

Check this Demo Fiddle

更新了 Demo Fiddle 没有警报——而是 FadeIn()元素

Updated Demo Fiddle no alert -- instead FadeIn() the element

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

Updated code to check if the element is inside the viewport or not. Thus this works whether you are scrolling up or down adding some rules to the if statement:

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

演示小提琴

这篇关于当用户滚动到特定元素时触发事件 - 使用 jQuery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆