gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 12:48:39 25 4
gpt4 key购买 nike

我正在尝试使用 This DEMO 在获取元素顶部时添加类或删除类 。这也是代码:

$(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 () { 但它不起作用!你能告诉我我做错了什么吗?谢谢

最佳答案

可以监听window对象的scroll事件,scroll事件和resize事件一样触发了很多次,为了提高效率,您可以限制处理程序,即处理程序在指定的超时后执行。

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

http://jsfiddle.net/UTCER/

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

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

关于javascript - 在滚动事件上添加和删除类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21744315/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com