额,说实话,我不太知道这个东西到底要怎么起名字
未拖动
拖动到最后
删除两个盒子
大概就是这样一个效果,进度条可以根据盒子个数自适应
html代码
css我就简单放一下
.box{
width: 100%;
padding: 0.2rem;
overflow: hidden;
box-sizing: border-box;
position: relative;
}
.controlBoxWidth{
width: 100%;
overflow: hidden;
height: 3rem;
}
.controlBoxScroll{
width: 100%;
overflow-x: auto;
white-space: nowrap;
}
.scrollBox{
width: 4rem;
margin-left: 0.2rem;
border: 1px solid red;
height: 2rem;
display: inline-block;
}
.scrollBox:nth-child(1){
margin: 0;
}
.scrollPage{
position: absolute;
bottom: 0.8rem;
width: 2rem;
height: 0.1rem;
background: gainsboro;
border-radius: 40rem;
overflow: hidden;
left: 50%;
margin-left: -1rem;
}
.nowPage{
background: gold;
height: 100%;
width: 0;
position: absolute;
}
html
<div class="box">
<div class="controlBoxWidth">
<div class="controlBoxScroll">
<div class="scrollBox">1</div>
<div class="scrollBox">2</div>
<div class="scrollBox">3</div>
<div class="scrollBox">4</div>
</div>
</div>
<div class="scrollPage">
<div class="nowPage"></div>
</div>
</div>
JS代码实现以及注释
window.onload = function(){
//给进度条一个宽度 根据滚动元素个数决定 百分比
var nowPageWidth = 100 / document.querySelector('.controlBoxScroll').children.length
document.querySelector('.nowPage').style.width = nowPageWidth + "%"
//获取进度条可滚动区域
var scrollPageRealScrollArea = 100 - nowPageWidth
//获取可滚动距离
var scrollWidthSize = document.querySelector('.controlBoxScroll').scrollWidth - document.querySelector('.controlBoxScroll').clientWidth
//滚动事件
document.querySelector('.controlBoxScroll').onscroll = function(e){
//当前滚动盒子滚动的进度 百分比
var scrollLeftSize = 100 - parseInt(((scrollWidthSize - this.scrollLeft) / scrollWidthSize)*100)
//滚动 左间距
document.querySelector('.nowPage').style.left = scrollPageRealScrollArea*(scrollLeftSize/100) + "%"
}
}
这里面比较绕,我起的名字也有可能比较长
这里讲解一下,
首先是整体思路 思路就是先计算可滚动距离
scrollWidth - clientWidth
不知道这个宽度分别代表的是什么请移步https://www.cnblogs.com/yuteng/articles/1894578.html
这里讲解了比较全面的元素距离屏幕各种距离 宽度的代码
然后我们用
取到的可滚动距离-scrollLeft
除以
可滚动距离
,就可以获取到当前滚动进度的一个百分比进度
这里我们做了一个跟据元素个数改变进度条长度的一个功能,这里我们求了一下元素个数,然后根据元素个数的百分比设置这个进度条的长度,之后计算底下进度条的可滚动区域
然后根据上面滚动的百分比,给那个进度条定位left一个百分比的值即可,
这里说一个小BUG,我把计算长度啥的都写在了scroll 事件外面,所以说如果你的屏幕被拉伸了 这个进度条就会不准,你可以把这些计算放在window.onsize事件里面
然后就没了