【问题标题】:Change element style on click单击更改元素样式
【发布时间】:2014-06-27 03:30:45
【问题描述】:

如果你有这样的风格。

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>

如果你使用这个js函数

function div_funkcija($div)
            {
                document.getElementById($div).style.display='none';
                document.getElementById($div+1).style.display='block';
            }

所以点击按钮隐藏 div1 并显示 div2 。

如何使div1的样式体以这张图片为背景“img01.jpg”,div2的样式体以背景图片“img02.jpg”为背景

你明白我的问题吗?

【问题讨论】:

  • div_funkcija(2);"这是错误的语法,你需要分配像onclick="div_funkcija(2);"这样的事件
  • @MaulikAnand 在打字时不小心错过了,但无论如何谢谢..
  • div_funkcija('2'); 将 ID 用引号括起来,因为您是作为字符串传递的,并且还要考虑更改不以数字开头的 ID

标签: javascript html css image background


【解决方案1】:

这是一个快速的 jsfiddle:http://jsfiddle.net/EhHr4/

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 id='1'>
  <input type='button' value="Answer"/>
</div>

<div id='2'>
  <input type='button' value="Answer 2"/>
</div>

CSS:

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

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

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

【讨论】:

  • 我有 10 个 div,你认为这是最好的解决方案。我也很想为整个身体设置背景图片。谢谢你的回答
  • 这绝对不是一个完美的答案,但很难真正理解您的要求,请随意调整上面的示例代码,这是一个好的开始。如果你想为整个 body 设置背景图像,那么只需定位 body 元素而不是任何 div 元素,并使用 javascript 中的 setAttribute 函数将类名添加到你的 body 元素。
  • 这帮了我'代码'
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-06
相关资源
最近更新 更多