How can I generate the opposite color according to current color?

前端 未结 11 635
北海茫月
北海茫月 2020-11-28 01:53

I\'m trying to create a color opposite of current color. I mean if current color is black, then I need to generate white.

Actually I have a text

11条回答
  •  [愿得一人]
    2020-11-28 02:42

    For Typescript lovers, here what I use:

    invertHex(hex: string) {
      if (hex.indexOf('#') === 0) {
        hex = hex.slice(1);
      }
    
      if (hex.length != 6) {
        console.warn('Hex color must be six hex numbers in length.');
        return '#' + hex;
      }
    
      hex = hex.toUpperCase();
      const splitNum = hex.split('');
      let resultNum = '';
      const simpleNum = 'FEDCBA9876'.split('');
      const complexNum = {
        A: '5', B: '4', C: '3', D: '2', E: '1', F: '0'
      };
    
      for (let i = 0; i < 6; i++) {
        if (!isNaN(Number(splitNum[i]))) {
          resultNum += simpleNum[splitNum[i]];
        } else if (complexNum[splitNum[i]]) {
          resultNum += complexNum[splitNum[i]];
        } else {
          console.warn('Hex colors must only include hex numbers 0-9, and A-F');
          return '#' + hex;
        }
      }
    
      return '#' + resultNum;
    }
    

提交回复
热议问题