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

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

问题描述

 < h1 id =scroll-to>> ;当滚动到时触发事件。< / h1> 

我想在用户滚动到h1时触发警报,或者在浏览器中
$ b

  $('#scroll-to')。scroll(function(){
alert('you已经滚动到h1!');
});

我该如何做?

可以计算元素的 offset ,然后将其与滚动 value like:

  $(window).scroll(function(){
var hT = $(' (),
wH = $(window).height(),$ b $如果(wS>(hT + hH-wH)){
console.log('view!'上的H1); $ b $($);
if b}
});

勾选 演示提琴




更新 演示提琴 无提示 - 而是FadeIn()元素






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

  if(wS>(hT + h $ w $)&&(hT> wS)&&&(wS + wH> hT + hH)){
//做某事
}

Demo小提琴


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

<h1 id="scroll-to">TRIGGER EVENT WHEN SCROLLED TO.</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!');
});

how do I do this?

解决方案

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


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


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
   }

Demo Fiddle

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

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