Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/powershell/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 单击即可更改图元样式_Javascript_Html_Css_Image_Background - Fatal编程技术网

Javascript 单击即可更改图元样式

Javascript 单击即可更改图元样式,javascript,html,css,image,background,Javascript,Html,Css,Image,Background,如果你有喜欢的款式 body { background: url(img01.jpg) no-repeat center center fixed; -webkit-background-size: cover; -moz-background-size: cover; -o-background-size: cover; background-size: cover; } 你有这样的按钮 <div id='1'> <input t

如果你有喜欢的款式

body { 
    background: url(img01.jpg) no-repeat center center fixed; 
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}
你有这样的按钮

<div id='1'>
<input type='button' onclick="div_funkcija(1);" value="Answer"> 
</div>

<div id='2'>
<input type='button' onclick="div_funkcija(2);" value="Answer 2"> 
</div>
所以点击按钮隐藏div1并显示div2

如何使div1具有以该图像为背景的样式体“img01.jpg”,而div2具有以背景图像“img02.jpg”为背景的样式体

你明白我的问题吗

这里有一个简单的问题:

Javascript:

var d1, d2;

d1 = document.getElementById("1");
d2 = document.getElementById("2");

d1.addEventListener("click", function() {
  // toggle display
  d2.style.display = "block";
  d1.style.display = "none";        
});

d2.addEventListener("click", function() {
  d1.style.display = "block";
  d2.style.display = "none";
});

d1.setAttribute("class", "background1");
d2.setAttribute("class", "background2");
HTML:


如需更多帮助,请在您的问题中提供更清晰的说明…

div_funkcija(2);“
这是错误的语法,您需要分配事件,如
onclick=“div\u funkcija(2);“
@MaulikAnand在打字时不小心漏掉了,但无论如何还是要谢谢你。
div_funkcija('2'))考虑到你正在以字符串的形式传递,也考虑改变你的ID不是从数字开始的,比如10 div的U,你认为这是最好的解决方案。我也很喜欢为整个身体设置背景图像。谢谢你的回答。这绝对不是一个完美的答案,但是很难真正理解Y。如果您要求,请随意调整上述示例代码,这是一个很好的开始。如果您想为整个主体设置背景图像,那么只需针对主体元素而不是任何div元素,并使用javascript中的setAttribute函数将类名添加到主体元素中。这对我“代码”很有帮助
var d1, d2;

d1 = document.getElementById("1");
d2 = document.getElementById("2");

d1.addEventListener("click", function() {
  // toggle display
  d2.style.display = "block";
  d1.style.display = "none";        
});

d2.addEventListener("click", function() {
  d1.style.display = "block";
  d2.style.display = "none";
});

d1.setAttribute("class", "background1");
d2.setAttribute("class", "background2");
<div id='1'>
  <input type='button' value="Answer"/>
</div>

<div id='2'>
  <input type='button' value="Answer 2"/>
</div>
.background1 {
   background: url(img01.jpg) no-repeat center center fixed; 
}

.background2 {
   background: url(img01.jpg) no-repeat center center fixed; 
}