Automatically change text color to assure readability

前端 未结 8 2042
生来不讨喜
生来不讨喜 2020-12-08 00:42

Users can set the background-color of a button through a textbox that accept RGB hexadecimal notation: ff00ff, ccaa22, etc. So I need to set the te

8条回答
  •  臣服心动
    2020-12-08 01:23

    var getContrastYIQ = function(color) {
      var hex = '#';
      var r, g, b;
      if (color.indexOf(hex) > -1) {
        r = parseInt(color.substr(1, 2), 16);
        g = parseInt(color.substr(3, 2), 16);
        b = parseInt(color.substr(5, 2), 16);
      } else {
        color = color.match(/\d+/g);
        r = color[0];
        g = color[1];
        b = color[2];
      }
    
      var yiq = ((r * 299) + (g * 587) + (b * 114)) / 1000;
      return (yiq >= 128) ? 'black' : 'white';
    }

    Thanks for the post ZetCoby! Had to adjust your "color.substr(" array position to account for the initial '#'; then it worked great! you could also use a color.replace('#',''); within the if block...

提交回复
热议问题