添加和删除类到jQuery onscroll [英] Add and remove class to jquery onscroll
本文介绍了添加和删除类到jQuery onscroll的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要为标题添加一个固定"类滚动并在以下脚本中向上滚动时将其删除,但不确定如何做到最好:
I need to add a 'fixed' class for the header on scroll and remove it when it's scrolled back up in the following script, but not sure how best to do it:
<script>
$(document).ready(function () {
var div = $('.header');
var div2 = $('.headerPlaceholder');
var start = $(div).offset().top;
$.event.add(window, "scroll", function () {
var p = $(window).scrollTop();
$(div).css('position', ((p) > start) ? 'fixed' : 'static');
$(div).css('top', ((p) > start) ? '0px' : '');
$(div2).css('display', ((p) > start) ? 'block' : 'none');
});
});
</script>
这将阻止它在每次向下滚动后触发事件,现在脚本中指定的CSS会发生这种情况,因此我需要添加一个类.
This stop it triggering the event after each scroll down which is what happens now with the CSS specified in the script, hence I need to add a class.
CSS:
.fixed {
position: fixed;
}
想法受到赞赏.
推荐答案
我已经将您的js转换为在身体上使用1类应用程序的情况下使用css
I have translated your js to use css with the application of 1 class to the body
$(document).ready(function () {
var start = $('.header').offset().top;
$.event.add(window, "scroll", function () {
var p = $(window).scrollTop();
if( p > start ) {
$('body').addClass('fixed');
} else {
$('body').removeClass('fixed');
}
});
});
CSS
body.fixed .header {
position: fixed;
top: 0;
}
body.fixed .headerPlaceholder {
display: block;
}
这篇关于添加和删除类到jQuery onscroll的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文