vue中实现web端横向滑动

2,766 阅读1分钟

要在Vue中实现横向滑动,需要使用一些CSS和JavaScript技巧来控制滑动操作

在模板中添加一个包含内容的div元素,并为它添加一个ref属性,以便在JavaScript中引用它。

      <div class="container" ref="container">
        <!-- 在这里添加要滑动的横向元素 -->
      </div>
   

使用CSS将这个div元素的子元素横向排列,并确保它们不会在父元素内换行。

    .container {
      display: flex; /* 将子元素横向排列 */
      white-space: nowrap; /* 避免子元素在父元素内换行 */
      overflow-x: auto; /* 显示横向滚动条 */
    }

编写JavaScript代码,以便在用户拖动div元素时滚动其内容。

    export default {
      mounted() {
        const container = this.$refs.container; // 获取容器元素
        let isDown = false, // 是否按下鼠标
            startX, // 鼠标起始位置
            scrollLeft; // 滚动条位置

        container.addEventListener('mousedown', (e) => {
          isDown = true;
          startX = e.pageX - container.offsetLeft; 
          scrollLeft = container.scrollLeft;
        });

        container.addEventListener('mouseup', () => {
          isDown = false;
        });

        container.addEventListener('mousemove', (e) => {
          if (!isDown) return;
          e.preventDefault();
          const x = e.pageX - container.offsetLeft;
          const walk = (x - startX) * 2;
          container.scrollLeft = scrollLeft - walk;
        });
      }
    };
    
    
    总结web端实现滑动,就是对鼠标按下、鼠标松开、鼠标移动事件进行监听  
    
    
    对了最后别忘了隐藏滚动条  
    
    ::-webkit-scrollbar {
      width: 0 !important;
    }
    ::-webkit-scrollbar {
      width: 0 !important;
      height: 0;
    }