在滚动事件上添加和删除类 [英] Add and Remove Class on Scroll Event
问题描述
我正在尝试通过使用 此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();
});
如果要将类添加到另一个元素,最有效的方法是使用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');
这篇关于在滚动事件上添加和删除类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!