第一次单击时,Javascript样式切换不起作用 [英] Javascript styling toggle doesn't work first click

查看:49
本文介绍了第一次单击时,Javascript样式切换不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作这个带有侧边栏菜单的小html应用程序,该菜单在单击时会弹出.除了只能在第二次单击后开始工作之外,它工作正常.第一次单击时什么都没有发生.

I'm making this little html app with a sidebar menu that pops up on click. It works fine except that it only starts to work after the second click. On the first click nothing happens.

CSS:

#menubalk{
   margin-left: -260px;
}

HTML:

<div id="menubutton">
   <img src="design/images/menu.png" id="menu" onclick="toggle()" alt=""/>
</div>

<div id="menubalk">
   <h5>Menu</h5>
</div>

JavaScript:

Javascript:

function toggle () {
  var el = document.getElementById("menubalk");
  var kop = document.getElementById("kop");
  var pag = document.getElementById("pagina");

  if ( el.style.marginLeft=="-260px" ) {
     el.style.marginLeft="0px";
     kop.style.marginLeft="260px";
     pag.style.marginLeft="260px";
  } else {
     el.style.marginLeft="-260px";
     kop.style.marginLeft="0px";
     pag.style.marginLeft="0px";
  }
}

我想我可能还必须在javascript中的某个位置设置边距,但我无法弄清楚.

I think I might have to set the margin somewhere in the javascript also but I can't figure it out.

非常感谢所有帮助!

推荐答案

style.marginLeft 正在查看您的内联样式.由于您尚未定义任何内联样式,因此最初 style.marginLeft 是未定义的.

style.marginLeft is looking at your inline styles. As you haven't defined any inline style initially style.marginLeft is undefined.

要解决此问题,您可以简单地反转if/else语句:

To fix this, you could simply reverse your if/else statement:

if ( el.style.marginLeft=="0px" )

这篇关于第一次单击时,Javascript样式切换不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆