有人可以帮帮我吗?当div水平滚动时,我试图在元素上添加(或显示)一个类,但在水平滚动时删除(或隐藏)该类。
我的代码无效。请看一下,谢谢!
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");
}
});
}
答案 0 :(得分:0)
不要检查零,检查他们的旧位置,如下:
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();
});
};