JS controls the container to scroll left and right through buttons

I implemented this function in the vue environment

1. Set the container to scroll and hide the scroll bar

.content {
  overflow-x: scroll;
}
.content::-webkit-scrollbar-track {
  display: none;
}

2. Add left and right arrow buttons and bind events

<div
  @mousedown="scrollLeft"
  @mouseup="stopScroll"
  @mouseleave="stopScroll"
>
  <el-button
    type="text"
    icon="el-icon-caret-left"
    class="scrollLeftBtn"
  ></el-button>
</div>
<div
  @mousedown="scrollRight"
  @mouseup="stopScroll"
  @mouseleave="stopScroll"
>
  <el-button
    type="text"
    icon="el-icon-caret-right"
    class="scrollRightBtn"
  ></el-button>
</div>

3. Implement left and right scrolling related methods

scrollLeft() {
    
    
  this.stopScroll();
  this.timer = setInterval(() => {
    
    
    this.$refs.content.scrollLeft -= step;
  }, 100);
},
scrollRight() {
    
    
  this.stopScroll();
  this.timer = setInterval(() => {
    
    
    this.$refs.content.scrollLeft += step;
  }, 100);
},
stopScroll() {
    
    
  clearInterval(this.timer);
},

4. If you need to judge whether the left and right buttons are displayed according to whether you have scrolled to the far left or right, you can bind the following method

handleScroll() {
    
    
  let contentRef = this.$refs.content;
  if(contentRef.scrollWidth != contentRef.clientWidth){
    
    
    if (contentRef.scrollLeft <= 0) {
    
    
      this.isScrollLeftBtn = false;
    } else {
    
    
      this.isScrollLeftBtn = true;
    }
    if (Math.ceil(contentRef.scrollLeft - (contentRef.scrollWidth - contentRef.clientWidth)) >= 0) {
    
    
      this.isScrollRightBtn = false;
    } else {
    
    
      this.isScrollRightBtn = true;
    }
  }else{
    
    
    this.isScrollLeftBtn = false;
    this.isScrollRightBtn = false;
  }
},

isScrollLeftBtn: Whether to display the left arrow button
isScrollRightBtn: Whether to display the right arrow button

Guess you like

Origin blog.csdn.net/weixin_44646763/article/details/130420177