Skip to content

Instantly share code, notes, and snippets.

@zenojunior
Created April 11, 2018 11:44
Show Gist options
  • Select an option

  • Save zenojunior/cdf92987f0b062a6a6a2c38082575ac3 to your computer and use it in GitHub Desktop.

Select an option

Save zenojunior/cdf92987f0b062a6a6a2c38082575ac3 to your computer and use it in GitHub Desktop.
Alterar texto com contraste de cor em relação ao background
<div id="exemple" style="background-color:ffff00">
<p class="text">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod.</p>
</div>
function rgbToArray(str)
{
let match = str.match(/rgba?\((\d{1,3}), ?(\d{1,3}), ?(\d{1,3})\)?(?:, ?(\d(?:\.\d?))\))?/);
return match ? {
red: match[1],
green: match[2],
blue: match[3]
} : {};
}
function changeTextByDiv(divBg, textElement)
{
let rgb = rgbToArray($(divBg).css('background-color'));
let yiq = ((rgb['red']*299)+(rgb['green']*587)+(rgb['blue']*114))/1000;
if(yiq >= 128){
$(textElement).css('color', 'black');
}else{
$(textElement).css('color', 'white');
}
}
changeTextByDiv('#exemple', 'p.text');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment