[英]JQuery add class when scroll vertically in a div and remove class when scroll horizontally
Can someone please help me out?有人可以帮我吗? I am trying to add (or show) a class on an element when a div scroll vertically but remove (or hide) that class when you scroll horizontally.我试图在 div 垂直滚动时在元素上添加(或显示)一个类,但在水平滚动时删除(或隐藏)该类。
My code below is not working.我下面的代码不起作用。 Please take a look, thanks!请看一下,谢谢!
window.onload = function() {
$('#myDiv').scroll(function () {
var hScroll = $(this).scrollLeft();
var vScroll = $(this).scrollTop();
if (hScroll > 0){
$('#element').removeClass("v_class").addClass("h_class");
}
if (vScroll > 0){
$('#element').removeClass("h_class").addClass("v_class");
}
});
}
Don't check against zero, check against their old position like this:不要检查零,检查他们的旧位置,如下所示:
window.onload = function() {
var oldScrollLeft = $('#myDiv').scrollLeft();
var oldScrollTop = $('#myDiv').scrollTop();
$('#myDiv').scroll(function () {
var hScroll = $(this).scrollLeft();
var vScroll = $(this).scrollTop();
//if the vertical scroll bar is in the same position after a scroll has occurred we must be scrolling horizontally, remove the vertical class and add the horizontal class.
if(oldScrollTop == vScroll){
$('#element').removeClass("v_class").addClass("h_class");
}
//else we must be scrolling vertically, remove the horizontal class and add the vertical class.
else{
$('#element').removeClass("h_class").addClass("v_class");
}
oldScrollLeft = $(this).scrollLeft();
oldScrollTop = $(this).scrollTop();
});
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.