在滚动事件上添加和删除类

编程入门 行业动态 更新时间:2024-10-27 10:19:28
本文介绍了在滚动事件上添加和删除类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试通过使用 此DEMO .这也是代码:

I am trying to add class or remove class on getting element top by using This DEMO . Here is the code as well:

$(document).ready(function () { var sec1_offset = $("#sec1").offset(); var sec2_offset = $("#sec2").offset(); var sec3_offset = $("#sec3").offset(); var sec4_offset = $("#sec4").offset(); var sec5_offset = $("#sec5").offset(); var sec6_offset = $("#sec6").offset(); var sec7_offset = $("#sec7").offset(); $("section").scroll(function () { if (sec4_offset.top < 100) { alert("You Are in Sec 4"); } }); });

我也将$("section").scroll(function () {更改为$(body).scroll(function () {和$(document).scroll(function () {,但是没有用! 您能告诉我我做错了吗?谢谢

I also change the $("section").scroll(function () { to $(body).scroll(function () { and $(document).scroll(function () { but it didn't work! Can you please let me know what I am doing wrong? Thanks

推荐答案

您可以侦听window对象的scroll事件,像resize事件一样触发scroll事件很多次,对于您可以限制处理程序的效率,即在指定的超时后执行处理程序.

You can listen to the scroll event of the window object, scroll event like the resize event is fired so many times, for efficiency you can throttle the handler, ie the handler is executed after a specified timeout.

$(document).ready(function () { var $sec = $("section"), handle = null; var $w = $(window).scroll(function () { // clear the timeout handle clearTimeout(handle); // throttling the event handler handle = setTimeout(function() { var top = $w.scrollTop(); // filtering the first matched element var $f = $sec.filter(function() { return $(this).offset().top + $(this).height() >= top; }).first().addClass('active'); $sec.not($f).removeClass('active'); }, 50); }).scroll(); });

jsfiddle/UTCER/

如果要将类添加到另一个元素,最有效的方法是使用index方法:

edit: If you want to add a class to another element, the most efficient way is using the index method:

// Cache the object outside the `scroll` handler var $items = $('#menu li'); // within the `setTimeout` context: var $f = $sec.filter(function() { return $(this).offset().top + $(this).height() >= top; }).first(); $items.removeClass('active').eq( $sec.index($f) ).addClass('active');

更多推荐

在滚动事件上添加和删除类

本文发布于:2023-11-10 23:00:13,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1576698.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:事件

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!