如下 input 的 type属性值是 HTML5 中新增的:javascript
color、date、datetime、datetime-local、month、week、time、email、number、range、search、tel 和 url。
设置input的type="range"
便可获得滑动条控件,以下:css
<input id="range" type="range" value="5" onchange="changeV()">
const range = document.getElementById('range'); function changeV() { console.log(range.value); }
下面咱们来使用一下上面的各个属性(示例:经过滑动条控制元素大小):html
<input type="range" id="range" value="20" min="0" max="200" step="1" onchange="changeV()"> <div class="box"></div> <script> const range = document.getElementById('range'); function changeV() { const boxL = parseInt(range.value); console.log(boxL); const box = document.getElementsByClassName('box')[0]; box.style.width = boxL + 'px'; box.style.height = boxL + 'px'; } </script>
示例中:前端
对应初始样式以下:
滑动滑动条后的gif图以下:
html5
先看两个不一样效果示例图:
上面两个红色框中的滑动条明显比默认样式好看不少,那么它们是如何实现的呢,接下来咱们讲实现过程:java
这里把对应滑动条的相关代码贴出来:git
<p>周期</p> <input type="range" id="dur" value="0.50" min="0" max="1.00" step="0.01" onchange="changeV()"> <p>速度</p> <input type="range" id="speed" value="0" min="0" max="5" step="0.01" onchange="changeV()">
/* 这里不考虑浏览器的兼容性 */ #control input[type="range"] { width: 100%; -webkit-appearance: none; height: 8px; border-radius: 4px; background: -webkit-linear-gradient(#ffa200, #ffa200) no-repeat white; background-size: 50% 100%; /* 由于周期默认value=0.50正好占50% */ } /* -webkit-slider-thumb仅对谷歌浏览器有效 */ #control input[type="range"]::-webkit-slider-thumb { -webkit-appearance: none; background-color: #aaa; width: 8px; height: 20px; border-radius: 4px; cursor: pointer; } #control input[type="range"]::-webkit-slider-thumb:hover { background: #666; } /* 左侧渐变色的写法,默认滑块在最左侧因此下面white为0% */ #control #speed { background: linear-gradient(to right, #ffa200, white 0%, white); background-size: 100% 100%; }
const duration = document.getElementById('dur'); const speed = document.getElementById('speed'); function changeV() { durVal = parseFloat(duration.value); spdVal = parseFloat(speed.value); const durationPercent = parseFloat(durVal, 2) * 100 const speedPercent = parseFloat((spdVal / 5), 2) * 100 duration.style.backgroundSize = `${durationPercent}%, 100%` speed.style.background = `linear-gradient(to right, #ffa200, white ${speedPercent}%, white` };
相信你们结合代码能够清晰的掌握两种滑动条的实现方法,这里就不过多解释了
gif效果局部展现:
web
演示地址canvas
前端是一个庞大的体系,不少知识在没用到的时候也许咱们根本不知道它多有用。就好比文中的滑动条,工做中很难碰到,一旦要用的时候咱们还得去琢磨一番,这里经过本身的讲解相信可让须要的人更好的使用滑动条功能,若是以为本文对你有所帮助不妨点个赞再走吧,谢谢啦!浏览器