简体   繁体   English

HTML5输入范围:将runnable-track的颜色更改为当前值

[英]HTML5 input range: change color of runnable-track up to current value

Using input type=range , how can I change the background color of the track in two colors so I can mimic the bootstrap slider? 使用input type=range ,如何将轨道的背景颜色更改为两种颜色,以便模仿引导滑块?

<input class="slider"
    type="range"
    min="0"
    max="100"
    step="1"
  />

在此输入图像描述

The method is similar to Color gradient check this one , So what you have to do is to mix the two colors basing on the current percentage of each one according to the Range Input , so in this case each side of the Input represents one color for sure. 该方法类似于“ 颜色渐变 检查”这一方法 ,因此您要做的是根据“ 范围输入”将两种颜色基于每种颜色的当前百分比进行混合,因此在这种情况下,“输入”的每一面代表一种颜色当然。

And to achieve that you need to play a little bit with mathematics, and therefor you need also to convert colors to a mathematical form like RGB . 为了达到这个目的,你需要玩一点数学,因此你还需要将颜色转换为像RGB这样的数学形式。

Then after that calculate the new color percentage, sum them together and finally you get the new color. 然后,计算出新的颜色百分比,将它们求和,最后得到新的颜色。

So you will need the following functions: 所以你需要以下功能:

<script>

//The following functions to convert the Hex color to RGB
function hexToR(h) {
    return parseInt((cutHex(h)).substring(0, 2), 16)
}
function hexToG(h) {
    return parseInt((cutHex(h)).substring(2, 4), 16)
}
function hexToB(h) {
    return parseInt((cutHex(h)).substring(4, 6), 16)
}
function cutHex(h) {
    return (h.charAt(0) == "#") ? h.substring(1, 7) : h
}

//Convert resulted color to Hex
function rgbToHex(R, G, B) {
    return "#" + toHex(R) + toHex(G) + toHex(B)
}
function toHex(n) {
    n = parseInt(n, 10);
    if (isNaN(n))
        return "00";
    n = Math.max(0, Math.min(n, 255));
    return "0123456789ABCDEF".charAt((n - n % 16) / 16)
            + "0123456789ABCDEF".charAt(n % 16);
}

//Mixing colors in one new color
function colorMix(color1, color2, value) {
    var color1Value = value;
    var color2Value = 100 - value;

    var colorR = ((color1Value / 100) * hexToR(color1)) + ((color2Value / 100) * hexToR(color2));
    var colorB = ((color1Value / 100) * hexToB(color1)) + ((color2Value / 100) * hexToB(color2));
    var colorG = ((color1Value / 100) * hexToG(color1)) + ((color2Value / 100) * hexToG(color2));

    return rgbToHex(colorR, colorG, colorB);
}

</script>  

And here is a working DEMO : Jsfiddle 这是一个有效的演示Jsfiddle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM