Javascript styling toggle doesn't work first click

守給你的承諾、 提交于 2019-11-28 14:42:59

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" )

element.style only search for inline style, to get actual style you can use getComputedStyle

i.e.
if ( window.getComputedStyle(el).marginLeft=="-260px" ) {...

Reference: https://developer.mozilla.org/en-US/docs/DOM/window.getComputedStyle

Note: For IE, this only works for IE9 or above.

Jaco Koster

With this line

if(el.style.marginLeft=="-260px") {

You are checking if the inline style of the element is a specific value. However, this style is set in the css. I recommend adding a className to the menu to expand it. You can check for this classname and add/remove it accordingly:

  if ( el.className == "expanded" ) {
     el.className = "";
  } else {
     el.className = "expanded";
  }

With this addition to the css:

#menubalk.expanded {
    margin-left:0;
}

You say you set the menu style in the JavaScript somewhere but I would actually recommend doing that as part of your initialisation, rather than setting the left margin with CSS.

I suspect (it's hard to see without an example) that on the first click the JavaScript is going straight to the else condition because it's not recognising that you've set the margin in CSS (or elsewhere). Then on the second click, JavaScript has been used to set the left margin so it can read it and perform accordingly.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!