h5自定义滚动条并监听事件

来源:互联网 发布:php开发app接口源码 编辑:程序博客网 时间:2024/06/08 19:43

代码加注释如下所示:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.container{
margin: 100px auto;
text-align: center;
}
/*取消轨道样式*/
input[type=range] {
-webkit-appearance: none;
width: 300px;
border-radius: 10px;
}
/*取消滑块样式*/
input[type=range]::-webkit-slider-thumb {
-webkit-appearance: none;
/*设置滑块样式*/
height: 25px;
    width: 25px;
    margin-top: -5px; /*使滑块超出轨道部分的偏移量相等*/
    background: #ffffff; 
    border-radius: 50%; /*外观设置为圆形*/
    border: solid 0.125em rgba(205, 224, 230, 0.5); /*设置边框*/
    box-shadow: 0 .125em .125em #3b4547; /*添加底部阴影*/
}
/*自定义轨道样式*/
input[type=range] {
height: 15px;
width: 300px;
border-radius: 10px;
box-shadow: 0 1px 1px #def3f8, inset 0 .125em .125em #0d1112; /*轨道内置阴影效果*/
background-color: #ccc;
background-image: linear-gradient(to right,#1F548F, #1F548F);
background-repeat: no-repeat;
background-size: 20% 100%;
}


/*原始的控件获取到焦点时,会显示包裹整个控件的边框,所以还需要把边框取消。*/
input[type=range]:focus {
outline: none;
}
</style>
</head>
<body>
<div class="container">
<p>这里显示进度条的值</p>
<button class="reduce">-</button>
<input type="range" max="99" min="19" step="1" value="30">
<button class="add">+</button>
</div>
<script>
var sliderBar = document.getElementsByTagName('input')[0];
var reduceBtn = document.getElementsByClassName('reduce')[0];
var addBtn = document.getElementsByClassName('add')[0];
var pEle = document.getElementsByTagName('p')[0];
var MINAGE = 19;
var MAxAGE = 99;


// sliderBar.style.width = '300px';


// 监听 滑动条值的改变 
sliderBar.addEventListener('input',function(e){

console.log(e.target.value)
pEle.innerHTML = e.target.value;
sliderBar.style.backgroundSize= (sliderBar.value - MINAGE)/80 * 100 + '% 100%'
})
// 点击 加号
reduceBtn.onclick = function(e){
sliderBar.value = Number(sliderBar.value) -1;
pEle.innerHTML = sliderBar.value -1;
sliderBar.style.backgroundSize= (sliderBar.value - MINAGE)/80 * 100 + '% 100%'
}
// 点击减号
addBtn.onclick = function(e){
sliderBar.value = Number(sliderBar.value) + 1;
pEle.innerHTML = Number(sliderBar.value) + 1;
sliderBar.style.backgroundSize= (sliderBar.value - MINAGE)/80 * 100 + '% 100%'
}
</script>
</body>
</html>


原创粉丝点击