2012-02-01 49 views
4

如何使用jQuery反轉元素的文本顏色?反轉特定元素的文本顏色(使用jQuery)

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

簡而言之,獲取顏色,將其轉化爲3個十進制值(它以十六進制IIRC形式返回)並從255中減去這些值。然後,您有你的R,G和B頻道,你使用'。.css()'來再次應用它們。 – Bojangles 2012-02-01 18:33:17

+2

http://webhole.net/2010/01/06/how-to-invert-an-elements-color/ – 2012-02-01 18:33:41

+2

http://stackoverflow.com/questions/4766201/javascript-invert-color-on-all-元素一頁 – j08691 2012-02-01 18:36:13

回答

1

首先負載http://www.phpied.com/files/rgbcolor/rgbcolor.js

然後,你可以做

$.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(); 

當用字(如「黑」)中指定的顏色屬性這也應該工作,而不是一個RGB值。但是,透明度不好。

9

有點晚,但遲到總比不到好:

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 
); 
+0

謝謝!簡單而有用! 將是真棒有一個函數,反轉十六進制和rgb沒有metter作爲參數傳遞 – 2013-11-12 19:38:33

1

我發現了一個巨大的 '十六進制顏色變頻' 功能中寫道馬特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; 
} 

來源是在這裏: http://www.mattlag.com/scripting/hexcolorinverter.php