当前位置: 动力学知识库 > 问答 > 编程问答 >

How do I change the color of all text and backgrounds with javascript?

问题描述:

I would like to write a script to reduce eye strain, which converts the color of all text on a page and all backgrounds for each element. (I guess the backgrounds would become darker and the text would then have to become lighter).

Are there any simple javascript techniques for making global changes to all elements on a page? Or would I have to somehow cycle through every element and check what the text color and background color are for that element (and how would I go about this if so)?

I realise there are probably different options with different levels of complexity, it would be interesting to have an outline of the various ways.

网友答案:

since you need to check each element's color individually, there is no global way of doing it with vanilla javascript.

you still need to select all elements and check their colors individually with a loop.

while you are going through the elements, you need to retrieve their "computed" colors, and alter them according to your requirements:

the snippet below will alter the contrast of the elements, making their background darker and text lighter, this can be adjusted via the global variable contrastChange according to your needs.

  var pageElements = document.querySelectorAll("*");

  //define a how much to change the contrast from 0 to 1

  var contrastChange = -0.3;

  //loop through the elements
  for (var i = 0; i < pageElements.length; i++) {
    //get the element's computed styles
    var elementComputedStyle = window.getComputedStyle(pageElements[i], "");
    //adjust the color
    var elemAdjustedColor = AdjustColor(elementComputedStyle.color, -contrastChange / 2);
    //adjust background color
    var elemAdjustedBGColor = AdjustColor(elementComputedStyle.backgroundColor, contrastChange);

    //set the new colors
    pageElements[i].style.color = elemAdjustedColor;
    pageElements[i].style.backgroundColor = elemAdjustedBGColor;
  }


function AdjustColor(color, brightness) {
  console.log(color);
  //the computed colors are retrieved as rgb(,,) for color attribute and
  //rgba(,,,) for background color, so we break them into
  //red green and blue components and adjust them according to the brightness
  var digits = /^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+(?:\.\d+)?))?\)$/.exec(color);
  
  //****UPDATE****
  //sometimes the color might be reported not by its rgb components, 
  //but rather by name like "transparent". in that case return the color unchanged
  //**************
  if (digits != null) {
    //adjust the colors
    var red = parseInt(digits[1]) + 255 * brightness;
    var green = parseInt(digits[2]) + 255 * brightness;
    var blue = parseInt(digits[3]) + 255 * brightness;
    //if color was rgba and had alpha component, we blend the color 
    //with white (because we dont know what was the color behind this element
    //and we are too lazy to check
    if (digits[4] != undefined) {
      alpha = 1 - digits[4];
      red = Math.round((alpha * (red / 255) + (alpha)) * 255);
      green = Math.round((alpha * (green / 255) + (alpha)) * 255);
      blue = Math.round((alpha * (blue / 255) + (alpha)) * 255);
    }
    // keep them in the 0-255 range
    if (red > 255) red = 255;
    if (red < 0) red = 0;
    if (green > 255) green = 255;
    if (green < 0) green = 0;
    if (blue > 255) blue = 255;
    if (blue < 0) blue = 0;

    return "rgb(" + Math.round(red) + "," + Math.round(green) + "," + Math.round(blue) + ")";
  } else {
    return color;
  }
};
<span style="background-color:rgba(255,0,0,0.1);">teasd asd asd ast</span>
<span style="background-color:#ffee99;">tesasdas dasd asd t</span>
<span style="background-color:#aaeecc;">teasd asd asd asd sst</span>
网友答案:

I would suggest this:

var elem= document.querySelectorAll("*");

for (var i = 0; i < myElements.length; i++) {
elem[i].style.setProperty("background", "#000000", "important");
elem[i].style.setProperty("color", "#ffffff", "important");
}

This will also overwrite "!important" rules.

You can extend the script easily by retrieving the current value (example: getProperty("background");) and add or replace it. A good function for adding values to a hex value can be seen here: Working with hex strings and hex values more easily in Javascript

网友答案:

The most efficient way should be to create a new style element with javascript and add a rule to this stylesheet to set the font color to black (or whatever you like). This way also new elements that are added to the page dynamically will obey the css rule.

function addCSSRule(sheet, selector, rules, index) {if("insertRule" in sheet) {sheet.insertRule(selector + "{" + rules + "}", index);}else if("addRule" in sheet) {sheet.addRule(selector, rules, index);}
}

var sheet = (function() {// Create the <style> tagvar style = document.createElement("style");// Add a media (and/or media query) here if you'd like!// style.setAttribute("media", "screen")// style.setAttribute("media", "only screen and (max-width : 1024px)")// WebKit hack :(style.appendChild(document.createTextNode(""));// Add the <style> element to the pagedocument.head.appendChild(style);return style.sheet;
})();

addCSSRule(sheet, "*", "color: white !important;");
addCSSRule(sheet, "*", "background-color: grey !important;");
h1 {
  color: red;
}

span {
  color: green;
}
<div>
  <h1>HEADING</h1>
  <span>Hallo World</span>
</div>  
网友答案:

more easiest way is

$("*").css({
       'background':'#333',
        'color':'#fff',
    }); 
分享给朋友:
您可能感兴趣的文章:
随机阅读: