How to get color value from gradient by percentage with javascript?

后端 未结 5 1111
离开以前
离开以前 2020-12-08 10:54

I have a fixed width div with gradient applied using css. I want to build slider based color picker based on this gradient.

When i drag the slider i calculate the pe

5条回答
  •  抹茶落季
    2020-12-08 11:52

    This is another way to convert percentage to color

    This exemple make a displayed value change from red to green depending on it's value (like for example in excel conditional formating):

    function(percentValue) {
      $(`#output`)
        // print the value
        .html(percentValue)
        // colorize the text, more red if it's close to 0
        // and more green as it approach 100
        .css({color: `rgb(${(100 - percent) *2.56}, ${percent *2.56},0)`})
    }
    

    Please see demo below:

    $('button').click( e => {
      const percent = Math.floor(Math.random()*100);
      const newElm = $(`${percent}
    `) .css({color: `rgb(${(100 - percent) *2.56},${percent *2.56},0)`}) $('body').append(newElm); })
    
    

提交回复
热议问题