首页 前端知识 css鼠标横向滚动并且不展示滚动条几种方法

css鼠标横向滚动并且不展示滚动条几种方法

2024-02-21 10:02:27 前端知识 前端哥 773 330 我要收藏

需求:实现内容超出之后使用属性滚轮进行左右查看超出内容,并且隐藏滚动条

1.不使用框架实现

每次滚动就滚动40px的距离

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <style>
      .container {
        width: 300px;
        overflow-x: hidden;
        white-space: nowrap;
        border: 1px solid #ccc;
      }
      .content {
        display: inline-block;
      }
    </style>
  </head>
  <body>
    <div class="container" onwheel="scrollHorizontally(event)">
      <div class="content">Content 1</div>
      <div class="content">Content 2</div>
      <div class="content">Content 3</div>
      <div class="content">Content 4</div>
      <div class="content">Content 5</div>
      <div class="content">Content 6</div>
    </div>

    <script>
      function scrollHorizontally(e) {
        e = window.event || e;
        var delta = Math.max(-1, Math.min(1, e.wheelDelta || -e.detail));
        document.querySelector(".container").scrollLeft -= delta * 40; // 每次滚动移动的距离
        e.preventDefault();
      }
    </script>
  </body>
</html>

效果:

2.vue2使用自定义指令实现

<template>
    <div style="height: 400px">
        <div class="container" v-horizontal-scroll>
            <div class="box">Content 1</div>
            <div class="box">Content 2</div>
            <div class="box">Content 3</div>
            <div class="box">Content 4</div>
            <div class="box">Content 5</div>
            <div class="box">Content 6</div>
            <div class="box">Content 1</div>
            <div class="box">Content 2</div>
            <div class="box">Content 3</div>
            <div class="box">Content 4</div>
            <div class="box">Content 5</div>
            <div class="box">Content 6</div>
        </div>
    </div>
</template>

<script>
export default {
    data() {
        return {};
    },
    directives: {
        'horizontal-scroll': {
            bind: function (el) {
                el.addEventListener('wheel', function (event) {
                    event.preventDefault();
                    el.scrollLeft += event.deltaY;
                });
            }
        }
    },
    mounted() {},
    methods: {}
};
</script>

<style lang="scss" scoped>
.container {
    width: 300px;
    overflow-x: hidden;
    white-space: nowrap;
    border: 1px solid #ccc;
    display: flex;
    overflow-x: scroll;
    overflow-y: hidden;
    white-space: nowrap;
    margin: 50px;
}
.container::-webkit-scrollbar {
    display: none;
}
.box {
    // display: inline-block;
}
</style>

效果

文章到此结束,希望对你有所帮助~~ 

转载请注明出处或者链接地址:https://www.qianduange.cn//article/2390.html
标签
评论
会员中心 联系我 留言建议 回顶部
复制成功!