我的背景变色了。现在如何更改文字的颜色?

时间:2019-09-28 04:21:15

标签: javascript

我是这里的新手,这是我的第一个问题。

每次浏览器刷新时,我的网站背景都会按顺序更改颜色,这很好(是)。

现在,我还想更改与我的身体关联的字体颜色属性,以便每次刷新时都可以使用不同的页面主题。

例如,刷新时:

红色背景带有蓝色文本,然后是橙色背景带有绿色文本,等等。

有什么主意如何将其优雅地添加到我现有的代码中?

我试图复制代码并以color属性(而不是background-color)为目标,只是看它是否可以工作,而不能。

谢谢您的帮助!

function loadNextImage1() {

  //declare image directory path and image array
  var colors = ["#red", "#blue", "#green"];
  colors[0] = "#red";
  colors[1] = "#blue";
  colors[2] = "#green";

  //get current cookie value
  var currentIndex = parseInt(getCookie());
  var background = colors[currentIndex];

  document.body.style.backgroundColor = background;

  //set next cookie index
  currentIndex += 1;
  currentIndex %= colors.length;
  setCookie(currentIndex);
}

function setCookie(someint) {
  var now = new Date();
  var addDays = now.getDate() + 7
  now.setDate(addDays); // cookie expires in 7 days
  var theString = 'imgID=' + escape(someint) + ';expires=' + now.toUTCString();
  document.cookie = theString;
}

function getCookie() {
  var output = "0";
  if (document.cookie.length > 0) {
    var temp = unescape(document.cookie);
    temp = temp.split(';');
    for (var i = 0; i < temp.length; i++) {
      if (temp[i].indexOf('imgID') != -1) {
        temp = temp[i].split('=');
        output = temp.pop();
        break;
      }
    }
  }
  return output;
}
<body onload="loadNextImage1();">
  <img id="ImageRefresh"/>
</body>

1 个答案:

答案 0 :(得分:0)

您可以拥有2套组合起来的组合

JS小提琴https://jsfiddle.net/vuo5pmdt/


function loadNextImage1() {
  //declare image directory path and image array
  var backgrounds = ["red", "blue", "green"];
  var foregrounds = ["white", "yellow", "black"];

  //get current cookie value
  var colorIndex = JSON.parse(localStorage.getItem('colorIndex') || '{"foreground":0, "background":0}');

  document.body.style.backgroundColor = backgrounds[colorIndex.background];
  document.body.style.color = foregrounds[colorIndex.foreground];

  //set next cookie index
  var next = {
    foreground: (colorIndex.foreground + 1) % foregrounds.length,
    background: (colorIndex.background + 1) % backgrounds.length
  };
  localStorage.setItem('colorIndex', JSON.stringify(next))
}
相关问题