“隐藏/显示”元素并更改按钮背景图像

时间:2015-03-06 14:09:13

标签: javascript html css

这段代码只能很好地隐藏/显示(Iamhiden)。

HTML:

 <nav id="Iamhiden"></nav>
 <button id="THeSummoner" onclick="toggle_visibility('Iamhiden');"></button>

CSS:

 #Iamhiden{}
 #THeSummoner{
      width: 30px;
      height: 30px;
      background-image: url(../Images/mobile-icon-1.png);
      background-repeat: no-repeat;
      margin: 22px 0px auto 0px;
      padding: 0;
      border-style: none;
      list-style: none;
      background-color: transparent;
}

JS:

function toggle_visibility(Iamhiden) {
   var e = document.getElementById(Iamhiden);
   if(e.style.display == 'block')
      e.style.display = 'none';
   else
      e.style.display = 'block';
}    

https://app.box.com/s/qy27mxja53tzucyzijbbiuhmd29bn40i https://app.box.com/s/8rom8cax3esmws62aj64p5yhwkeass8k

但我不希望它隐藏/显示(Iamhiden)我只想让它改变(THeSummoner)的背景图像。

JS - 2:

function toggle_visibility(Iamhiden) {
   var e = document.getElementById(Iamhiden);
   if(e.style.display == 'block')
      e.style.display = 'none';
      **document.getElementById(THeSummoner).style.background-image=url(../Images/mobile-icon-1.png);**
   else
      e.style.display = 'block';
      document.getElementById(THeSummoner).style.background-image=url(../Images/xmnu.png);
}

我尝试过 JS - 2 ,但它根本不起作用。

1 个答案:

答案 0 :(得分:0)

没有 THeSummoner 变量,因此您必须将元素Id指定为字符串,而不是变量:

document.getElementById('THeSummoner')

现在您可以像这样更改元素的背景图像:

document.getElementById('THeSummoner').style.backgroundImage = "url('type_path_here')";

以下是一个示例:http://jsfiddle.net/42joe84p/2/