I need to listen to the scrolling event of the page and according to the scrolling direction, it should be able to change css classes of elements. If scrolling happens for right/left, one css class should be added to an element and from another element that css class should be removed. if scrolling happens for down/up, above change should be happened in opposite way. My attempt is as below.
created() {
window.addEventListener("scroll", this.handleScroll);
},
destroyed() {
window.removeEventListener("scroll", this.handleScroll);
},
data() {
return {
isDisableScrollableForTable: false,
isDisableScrollableForSub: false
};
}
methods: {
handleScroll(event) {
$el.on("scroll", function() {
// get current scroll position
const currY = $el.scrollTop();
const currX = $el.scrollLeft();
// determine current scroll direction
const currDir = {
x:
currX > lastPos.x ? "right" : currX === lastPos.x ? "none" : "left",
y: currY > lastPos.y ? "down" : currY === lastPos.y ? "none" : "up"
};
if (currDir.x == "left" || currDir.x == "right") {
this.isDisableScrollableForSub = true;
this.isDisableScrollableForTable = false;
console.log("horizontal scroll");
} else if (currDir.y == "up" || currDir.y == "down") {
this.isDisableScrollableForSub = false;
this.isDisableScrollableForTable = true;
console.log("vertical scroll");
}
// update last scroll position to current position
lastPos.y = currY;
lastPos.x = currX;
});
}
}
<div
id="subScrolling"
:class="{ isDisableScrollable: isDisableScrollableForSub }">
</div>
<div
id="tableScrolling"
:class="{ isDisableScrollable: isDisableScrollableForTable }">
</div>
Here scrolling direction could be identified correctly. But css classes were not bounded. Where I was get wrong and how can I fix this?
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…