How do I write a RGB color value in JavaScript?

前端 未结 6 1533
不知归路
不知归路 2020-12-28 13:09

I am trying to change the color of the function swapFE() below and I can\'t figure out how to write it. I was told to change the color of the phrase node to the color value

相关标签:
6条回答
  • 2020-12-28 13:24
    dec2hex = function (d) {
      if (d > 15)
        { return d.toString(16) } else
        { return "0" + d.toString(16) }
    }
    rgb = function (r, g, b) { return "#" + dec2hex(r) + dec2hex(g) + dec2hex(b) };
    

    and:

    parent.childNodes[1].style.color = rgb(155, 102, 102);
    
    0 讨论(0)
  • 2020-12-28 13:31

    try:

    parent.childNodes[1].style.color = "rgb(155, 102, 102)"; 
    

    Or

    parent.childNodes[1].style.color = "#"+(155).toString(16)+(102).toString(16)+(102).toString(16);
    
    0 讨论(0)
  • 2020-12-28 13:33

    Here's a simple function that creates a CSS color string from RGB values ranging from 0 to 255:

    function rgb(r, g, b){
      return "rgb("+r+","+g+","+b+")";
    }
    

    Alternatively (to create fewer string objects), you could use array join():

    function rgb(r, g, b){
      return ["rgb(",r,",",g,",",b,")"].join("");
    }
    

    The above functions will only work properly if (r, g, and b) are integers between 0 and 255. If they are not integers, the color system will treat them as in the range from 0 to 1. To account for non-integer numbers, use the following:

    function rgb(r, g, b){
      r = Math.floor(r);
      g = Math.floor(g);
      b = Math.floor(b);
      return ["rgb(",r,",",g,",",b,")"].join("");
    }
    

    You could also use ES6 language features:

    const rgb = (r, g, b) => 
      `rgb(${Math.floor(r)},${Math.floor(g)},${Math.floor(b)})`;
    
    0 讨论(0)
  • 2020-12-28 13:35

    I am showing with an example of adding random color. You can write this way

    var r = Math.floor(Math.random() * 255);
    var g = Math.floor(Math.random() * 255);
    var b = Math.floor(Math.random() * 255);
    var col = "rgb(" + r + "," + g + "," + b + ")";
    parent.childNodes[1].style.color = col;
    

    The property is expected as a string

    0 讨论(0)
  • 2020-12-28 13:39

    ES6 (template literal) helper functions:

    function rgba(r, g, b, a=1){
        return `rgba(${r}, ${g}, ${b}, ${a})`
    }
    function rgb(r, g, b){
        return `rgb(${r}, ${g}, ${b})`
    }
    
    0 讨论(0)
  • 2020-12-28 13:45

    this is better function

    function RGB2HTML(red, green, blue)
    {
        var decColor =0x1000000+ blue + 0x100 * green + 0x10000 *red ;
        return '#'+decColor.toString(16).substr(1);
    }
    
    0 讨论(0)
提交回复
热议问题