Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
342 views
in Technique[技术] by (71.8m points)

javascript - scrolling direction to change elements class dynamically in vue js

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?

question from:https://stackoverflow.com/questions/65855516/scrolling-direction-to-change-elements-class-dynamically-in-vue-js

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to use an arrow function to preserve the this context:

$el.on("scroll", () => {
...
})

Otherwise the callback function injects its own this


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...