css自定义滚动条

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title></title>
  <style type="text/css">
    * {
      padding: 0;
      margin: 0;
    }

    .wrap {
      width: 400px;
      height: 400px;
      border: 2px solid deeppink;
      margin: 0 auto;
      overflow: hidden;
      position: relative;
    }

    .box-middle {
      height: 100%;
      overflow: auto;
      width: 200%;
      /* border: 2px solid blue; */
      box-sizing: border-box;
    }

    .box {
      width: 50%;
    }

    .bar {
      background: #000;
      width: 10px;
      position: absolute;
      top: 0;
      right: 0;
      /* border: 2px solid red; */
      box-sizing: border-box;
      z-index: 100;
    }

    .bar_bg {
      background: #fff;
      width: 10px;
      height: 100%;
      position: absolute;
      top: 0;
      right: 0;
      /* border: 2px solid red; */
      box-sizing: border-box;
      z-index: 10;
    }

    .s1 {
      height: 400px;
      background: pink;
    }

    .s2 {
      height: 400px;
      background: deeppink;
    }

    .s3 {
      height: 400px;
      background: deepskyblue;
    }
  </style>
</head>

<body>
  <div class="wrap" id="wrap">
    <div class="box-middle" id="boxMidle">
      <div class="box" id="content">
        <div class="s1">内容1</div>
        <div class="s2">内容2</div>
        <div class="s3">内容3</div>
      </div>
    </div>
    <div class="bar" id="bar"></div>
    <div class="bar_bg"></div>
  </div>

</body>

<script>
  var $wrap = document.getElementById("wrap");
  var $boxMidle = document.getElementById("boxMidle");
  var $content = document.getElementById("content");
  var $bar = document.getElementById("bar");
  $content.style.width = $wrap.clientWidth + "px";  //内容的宽度
  var rate = $boxMidle.clientHeight / $boxMidle.scrollHeight;  //滚动条高度的比例,也是滚动条top位置的比例
  var barHeight = rate * $boxMidle.clientHeight;  //滚动条的 bar 的高度
  if (rate < 1) {
    //需要出现滚动条,并计算滚动条的高度
    $bar.style.height = barHeight + "px";
  } else {
    //不需要出现滚动条
    $bar.style.display = "none";
  }

  $boxMidle.onscroll = function (e) {
    console.log("offsetHeight" + this.offsetHeight); //height + padding + border
    console.log("clientHeight" + this.clientHeight); // height + padding
    console.log("scrollHeight" + this.scrollHeight); //内容的高度(所有子元素高度和) + padding
    console.log(this.scrollTop);
    $bar.style.top = this.scrollTop * rate + "px";
  }
</script>

</html>

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值