一行代码实现鼠标横向滚动💪

🧑‍💻 写在开头

点赞 + 收藏 === 学会🤣🤣🤣

在项目中我们可能会遇到当鼠标在某个区域内,我们希望滚动鼠标里面的内容可以横向滚动;

比如我们一些常见的后台状态栏:

那这种该怎么写?请看栗子

 

 代码如下:

<template>
  <div>
    <div class="top">
      <div class="title">横 向 滚 动</div>
    </div>
    <div ref="container" class="container">
      <div class="contents" v-for="item in 20" :key="item">{{ item }}</div>
    </div>
    <div class="bottom"></div>
  </div>
</template>

<script>
export default {
  data() {
    return {};
  },
  mounted() {
    this.horizontalScrolling();
  },
  methods: {
    // 水平滚动
    horizontalScrolling() {
      const container = this.$refs.container;
      container.addEventListener("wheel", (e) => {
        e.preventDefault();
        container.scrollLeft += e.deltaY;
      });
    },
  },
};
</script>

<style scoped>
.container {
  margin: 20px 0;
  display: flex;
  align-items: center;
  height: 400px;
  overflow-x: scroll;
  background: #000;
  /* 隐藏滚动条 */
  scrollbar-width: none;
  -ms-overflow-style: none;
}
.contents {
  width: 600px;
  height: 300px;
  flex-shrink: 0; /* 关闭收缩 */
  margin: 0 20px;
  border-radius: 16px;
  text-align: center;
  color: #ffffff;
  line-height: 300px;
  font-size: 60px;
  background: linear-gradient(270deg, #ffd700 0%, #be8f00 50%, #ffdd00 100%);
}
</style>

主要代码还是这一块:

    horizontalScrolling() {
      const container = this.$refs.container;
      container.addEventListener("wheel", (e) => {
        e.preventDefault();
        container.scrollLeft += e.deltaY;
      });
    },

😄一行代码是不可能滴,代码压缩那说不准可以,哈哈哈哈哈😄

如果对您有所帮助,欢迎您点个关注,我会定时更新技术文档,大家一起讨论学习,一起进步。

 

posted @ 2024-06-17 19:22  林恒  阅读(64)  评论(0编辑  收藏  举报