通过 window.getComputedStyle 更改背景图片

Changing background image through window.getComputedStyle

我正在尝试编写一个函数,通过单击按钮从 3 个不同的选项中循环 background-image,但代码无法正常工作。也许有人能说出原因...

function changeBackground (){
  console.log('change background');
  var b = document.getElementById('mainbody');
  var bstyle = window.getComputedStyle(b, null).getPropertyValue('background-image');
  if (bstyle == "url('strawberry.png')") {
    b.style.backgroundImage = "url('raspberry.png')";
  } else if (bstyle == "url('raspberry.png')"){
    b.style.backgroundImage = "url('blueberry.png')";
  } else {
    b.style.backgroundImage = "url('strawberry.png')";
  }
}

例如,这段用于更改 font-size 的代码非常有效。

function changeSize (){ 
  console.log('changing font size');
  var s = document.getElementById('clock');
  var sstyle = window.getComputedStyle(s, null).getPropertyValue('font-size');
  if (sstyle == "25px") {
    s.style.fontSize = "50px";
  } else{
    s.style.fontSize = "25px";
  }
}
var x = 0;
var pics = ['strawberry.png', 'raspberry.png', 'blueberry.png'];
function changeBackground (){
  console.log('change background');
  var b = document.getElementById('mainbody');
  b.style.backgroundImage = 'url('+pics[(x++) % pics.length]+')';
}

我建议使用一个计数器变量,如上所示,以跟踪函数被调用的次数并相应地更新背景。

遇到的问题是当JavaScript更改背景图像URL时,完整的绝对路径被保存为CSS中的计算值。但是,稍后与它进行比较时,此绝对路径与最初使用的相对路径不匹配。显然,其他属性(例如 font-size)不会遇到同样的问题。