HTML5新特性——自定義滑動條(input[type="range"])


HTML 4.01 與 HTML5之間的差異

以下 input 的 type屬性值是 HTML5 中新增的:

color、date、datetime、datetime-local、month、week、time、email、number、range、search、tel 和 url。

input的type屬性

設置input的type="range"即可得到滑動條控件,如下:

<input id="range" type="range" value="5" onchange="changeV()">
const range = document.getElementById('range');

function changeV() {
  console.log(range.value);
}

在這里插入圖片描述

滑動條對應屬性

  • max - 規定允許的最大值。
  • min - 規定允許的最小值。
  • step - 規定合法數字間隔。
  • value - 規定默認值。

下面我們來使用一下上面的各個屬性(示例:通過滑動條控制元素大小):

<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>

示例中:

  • min - 0
  • max - 200
  • step - 1
  • value - 20

對應初始樣式如下:
在這里插入圖片描述
滑動滑動條后的gif圖如下:
在這里插入圖片描述

如何讓滑動條控件更加好看

先看兩個不同效果示例圖:
在這里插入圖片描述
上面兩個紅色框中的滑動條明顯比默認樣式好看很多,那么它們是如何實現的呢,接下來我們講實現過程:

兩個不同樣式滑動條的實現過程

這里把對應滑動條的相關代碼貼出來:

<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效果局部展示:
在這里插入圖片描述

文章中用到的示例演示地址

演示地址

寫在最后

前端是一個龐大的體系,很多知識在沒用到的時候也許我們根本不知道它多有用。就比如文中的滑動條,工作中很難碰到,一旦要用的時候我們還得去琢磨一番,這里通過自己的講解相信可以讓需要的人更好的使用滑動條功能,如果覺得本文對你有所幫助不妨點個贊再走吧,謝謝啦!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2026 CODEPRJ.COM