Invert text-color of a specific element (using jQuery)

喜你入骨 提交于 2019-12-29 07:12:06

问题


How do I invert the text-color of an element using jQuery?

<div style="color: rgb(0, 0, 0)">Invert me</div>

回答1:


A bit late but better late than never:

function invert(rgb) {
  rgb = Array.prototype.join.call(arguments).match(/(-?[0-9\.]+)/g);
  for (var i = 0; i < rgb.length; i++) {
    rgb[i] = (i === 3 ? 1 : 255) - rgb[i];
  }
  return rgb;
}

console.log(
  invert('rgba(255, 0, 0, 0.3)'), // 0, 255, 255, 0.7
  invert('rgb(255, 0, 0)'), // 0, 255, 255
  invert('255, 0, 0'), // 0, 255, 255
  invert(255, 0, 0) // 0, 255, 255
);



回答2:


First load http://www.phpied.com/files/rgbcolor/rgbcolor.js

Then you can do

$.fn.invertElement = function() {
  var prop = 'color';

  if (!this.css(prop)) return;

  var color = new RGBColor(this.css(prop));
  if (color.ok) {
    this.css(prop, 'rgb(' + (255 - color.r) + ',' + (255 - color.g) + ',' + (255 - color.b) + ')');
  }
};

$('div').invertElement();

This should also work when the color property is specified with a word (like "black") rather than an RGB value. It won't work well with transparency, however.




回答3:


I found a great 'Hexadecimal Color Inverter' function wrote by Matt LaGrandeur (http://www.mattlag.com/)

function invertHex(hexnum){
  if(hexnum.length != 6) {
    console.error("Hex color must be six hex numbers in length.");
    return false;
  }

  hexnum = hexnum.toUpperCase();
  var splitnum = hexnum.split("");
  var resultnum = "";
  var simplenum = "FEDCBA9876".split("");
  var complexnum = new Array();
  complexnum.A = "5";
  complexnum.B = "4";
  complexnum.C = "3";
  complexnum.D = "2";
  complexnum.E = "1";
  complexnum.F = "0";

  for(i=0; i<6; i++){
    if(!isNaN(splitnum[i])) {
      resultnum += simplenum[splitnum[i]]; 
    } else if(complexnum[splitnum[i]]){
      resultnum += complexnum[splitnum[i]]; 
    } else {
      console.error("Hex colors must only include hex numbers 0-9, and A-F");
      return false;
    }
  }

  return resultnum;
}

Source is here: http://www.mattlag.com/scripting/hexcolorinverter.php



来源:https://stackoverflow.com/questions/9101224/invert-text-color-of-a-specific-element-using-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!