试图通过选择器选项设置身体背景图像

时间:2018-11-21 06:29:12

标签: html

通过选择器选择每个选定的项目时,我试图更改我的背景图像,我想知道是否有人可以帮助我解决我做错的事情。当前,选择每个选项而不是正文时,会将选择器选项设置为背景。

<body id="mainBody" background="resources/imgs/background2.jpg" >
<select onchange="changeBackGround();" id="selectBackGround">
<option value="Original">Original</option>
<option value="GreyScale">GreyScale</option>
<option value="Colorful">Colorful</option>
</select>



 var changeBackGround = function(){
var mainBody = document.getElementById("selectBackGround");
if(document.getElementById("selectBackGround").value === "Original"){
      mainBody.style.backgroundImage = "url('resources/imgs/background2.jpg')";
}else if(document.getElementById("selectBackGround").value === "GreyScale"){
      mainBody.style.backgroundImage = "url('resources/imgs/greyscale.jpg')";
  }else{
      mainBody.style.backgroundImage = "url('resources/imgs/colored.jpg')";
  }
  mainBody.style.backgroundImage = document.getElementById("selectBackGround").value;
};

1 个答案:

答案 0 :(得分:0)

更改

var mainBody = document.getElementById("selectBackGround");

var mainBody = document.getElementById("mainBody");

您正在将背景应用于mainBody而不是选择背景。

 var changeBackGround = function(){
var mainBody = document.getElementById("mainBody");
if(document.getElementById("selectBackGround").value === "Original"){
      mainBody.style.backgroundImage = "url('resources/imgs/background2.jpg')";
}else if(document.getElementById("selectBackGround").value === "GreyScale"){
      mainBody.style.backgroundImage = "url('resources/imgs/greyscale.jpg')";
  }else{
      mainBody.style.backgroundImage = "url('resources/imgs/colored.jpg')";
  }
  mainBody.style.backgroundImage = document.getElementById("selectBackGround").value;
};
<body id="mainBody" background="resources/imgs/background2.jpg" >
<select onchange="changeBackGround();" id="selectBackGround">
<option value="Original">Original</option>
<option value="GreyScale">GreyScale</option>
<option value="Colorful">Colorful</option>
</select>