Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.6k 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?


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

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...