How to increment / decrement hex color values with javascript / jQuery

前端 未结 3 1262
说谎
说谎 2021-02-06 07:33

Is it possible to increment or decrement hex color values on a step-by-step basis in jQuery / javascript?

What I would like to do is something like this:

Adapt

3条回答
  •  [愿得一人]
    2021-02-06 08:10

    Well you can do it simply by this way:

    var incrementColor = function(color, step){
        var colorToInt = parseInt(color.substr(1), 16),                     // Convert HEX color to integer
            nstep = parseInt(step);                                         // Convert step to integer
        if(!isNaN(colorToInt) && !isNaN(nstep)){                            // Make sure that color has been converted to integer
            colorToInt += nstep;                                            // Increment integer with step
            var ncolor = colorToInt.toString(16);                           // Convert back integer to HEX
            ncolor = '#' + (new Array(7-ncolor.length).join(0)) + ncolor;   // Left pad "0" to make HEX look like a color
            if(/^#[0-9a-f]{6}$/i.test(ncolor)){                             // Make sure that HEX is a valid color
                return ncolor;
            }
        }
        return color;
    };
    

    For steps:

    • 1 by 1 to 256 increment last color
    • 256 by 256 increment middle color
    • 65536 by 65536 increment first color

    A running example here: http://jsfiddle.net/a3JbB/

提交回复
热议问题