Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
339 views
in Technique[技术] by (71.8m points)

html - Javascript styling toggle doesn't work first click

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:

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";
  }
}

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

All help is greatly appreciated!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...