关于模拟一个滚动条的实现------横向滚动条 原生 html css js

关于模拟一个滚动条的实现------横向滚动条 原生 html css js

在日常开发中会遇到一些时候,在实现内部滚动的同时,也希望用户看到当前的滚动位置

但是 overflow: auto; 的滚动条太难看了,尽管可以重些一些样式,但是移动端仍不支持。

无奈只能做出妥协,遂想 可否实现自定义模拟一个滚动指示器出来,以求满足业务要求。

以下是实例
在这里插入图片描述

下面附详细代码不再过多赘述,直接运行即可 注释中有说明

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    main {
    
    
      width: 100%;
      height: 200px;
      background-color: #ffcdcd;
      overflow-x: auto;
    }

    main>div {
    
    
      width: 120vw;
    }

    footer {
    
    
      width: 100px;
      height: 10px;
      background-color: #d1eff8;
      margin: 20px auto;
      border-radius: 5px;
    }

    footer>div {
    
    
      width: 50px;
      height: 10px;
      background-color: #38616d;
      border-radius: 5px;
    }
  </style>
</head>

<body>
  <!-- 滚动元素的父盒子 -->
  <main>
    <!-- 内部滚动的盒子 该元素内容超出 -->
    <div>
      dasdasgddddddddddddddddddddddddddddddddddddddddddd
    </div>
  </main>
  <!-- 用来模拟滚动条区域 -->
  <footer>
    <!-- 模拟当前滚动的位置 -->
    <div class="thisDiv">
    </div>
  </footer>

  <!-- 显示滚动的百分比 -->
  <p id="jindu">0.00%</p>

  <script>
    // 获取滚动元素的父元素
    let mainBox = document.querySelector('main')

    let scollAllWidth = document.querySelector('footer').offsetWidth
    let scollWidth = document.querySelector('footer>div').offsetWidth

    let thisScolljd = scollAllWidth - scollWidth  // 代表模拟滚动条的滚动大小

    // 给元素添加scoll事件,方便获取滚动的具体数据
    mainBox.addEventListener('scroll', (e) => {
    
    
      // console.log(e)
      const {
    
     target } = e
      // console.log(target.offsetWidth);  // 可视的宽度
      // console.log(target.scrollLeft);  // 当前滚动的宽度
      // console.log(target.scrollWidth); // 滚动区域总宽度
      // console.log(target.scrollWidth - target.offsetWidth);  // 总滚动的长度
      let thisJd = target.scrollLeft / (target.scrollWidth - target.offsetWidth)   // 当前滚动的距离 / 代表滚动的总距离
      document.querySelector('#jindu').innerHTML = (thisJd * 100).toFixed(2) + '%'   // 滚动的百分比
      document.querySelector('.thisDiv').style.marginLeft = `${
      
      thisScolljd* thisJd}px`  // 根据上放计算进度,改变下方模拟的位置
      // console.log((thisJd * 100).toFixed(2), '%');  // 当前滚动的百分比
    });
  </script>
</body>

</html>

以上案例是一个基本的效果,实际使用须隐藏原生滚动条即可。 隐藏滚动条百度很多, 可以在父元素添加 overflow:hidden, 只要高度或者宽度小于子元素,即可隐藏 纵/横向滚动条了。
想必各位都懂,就未出现在代码中。

猜你喜欢

转载自blog.csdn.net/qq_46634851/article/details/129553402