自定义滚动条

当我们给元素加上 overflow: auto; 的时候,就会出现滚动条,然而浏览的不同,滚动条的样式大不一样,有些甚至非常丑。参考:https://www.jb51.net/article/169734.htm

  • 实现步骤
    1.我们可以先根据内容求出滚动条的高度
    2.当鼠标进入时容器,鼠标按住,则滚动条跟鼠标在容器的盒子走动
    3.滚动条滚动,根据定位,内容盒子跟着滚动
    4.鼠标离开则不滚动
  • 注意事项
    1.scrollTop的值不可以加单位
    2.网页缩放比例会影响效果实现;
    3.滚动条 bar 是根据内容的多少,高度不一样的,这个需要动态的计算
    4.滚动条 bar 的 top 位置 和 内容scrollTop 的关系。
  • 知识点
    1.offsetHeight : height + padding + border
    2.clientHeight : height + padding
    3.scrollHeight : 内容的高度(所有子元素高度和) + paddings
    4.bar的高度 / wrap的高度 = wrap的高度 / wrap 内容部子元素的高度和 ; 此时忽略 wrap 的padding:0
    5.bar的top / wrap的scrollTop = wrap的高度 / wrap 内容部子元素的高度和 ;
    6.需要注意,当比例 的 值 小于 1 的时候,说明 这个时候没有出现滚动条。
<div class="wrap" id="wrap">
        <div class="content_div" id="boxMidle">
            <div class="content" id="content">
                <h1>楔子</h1>
                <p>
                                测试内容 测试内容 测试内容 测试内容 测试内容 测试内容 测试内容 测试内容 测试内容 测试内容 测试内容 测试内容 测试内容 测试内容 测试内容 测试内容 测试内容 测试内容 测试内容 测试内容 测试内容 测试内容 测试内容 测试内容 测试内容 测试内容 测试内容 测试内容 测试内容 测试内容 测试内容 测试内容 测试内容 测试内容 测试内容 测试内容 测试内容 测试内容 测试内容 测试内容 测试内容 测试内容 测试内容 测试内容 测试内容 测试内容 测试内容 测试内容 测试内容 测试内容 测试内容 测试内容 测试内容
                                </p>
            </div>
        </div>
        <div class="bar" id="bar"></div>
    </div>
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";
  $bar.style.display = "block";
}else{
  //不需要出现滚动条
  $bar.style.display = "none";
}
$boxMidle.onscroll = function(e){
  console.log("rate"+rate); //height + padding + border
  console.log("barHeight"+barHeight);
  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";
}
.wrap{
    width: 800px;
    height: 300px;
    border: 1px solid #ddd;
    margin: 0 auto;
    overflow: hidden;
    position: relative;
}

.wrap .content_div{
    height: 100%;
    overflow: auto;
    width: 200%;
}

.wrap .content{
    width: 50%;
}

h1{
    padding: 0 10px;
}
p{
    padding: 0 10px;
}

.wrap .scroll_div{
    height: 100%;
    width: 5px;
    background: #e23;
    position: absolute;
    top: 0;
    right: 0;
}

.wrap .bar{
    background: #ddd;
    width: 5px;
    position: absolute;
    top: 0;
    right: 0;
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
禁止转载,如需转载请通过简信或评论联系作者。

相关阅读更多精彩内容

友情链接更多精彩内容