onclick和类切换问题?

时间:2014-11-29 16:44:22

标签: javascript html css onclick toggle

我有一个< a>带有文本“menu”的元素和旁边的“汉堡包”符号,点击时会激活它。当我点击它或点击菜单文本时,我只想让汉堡符号动画化。它不起作用。

HTML:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title></title>
</head>
<body>
    <div id="st-trigger-effects" class="column">
        <a id="menu_button" href="#" data-effect="st-effect-1" >MENU</a>
        <a id="nav-toggle" href="#" data-effect="st-effect-1" ><span></span></a>
    </div>
</body>
</html> 

的CSS:

* { margin: 0%; padding: 0%; text-decoration: none; list-style-type: none; font-size: 100%; }

body {
  background: #000;
}


#menu_button {
    position: absolute;
    left: 6.79%;
    margin-top: 1.5%;
    z-index: 999999;
    color: #fff;
    font-size: 16px;
}




#nav-toggle { position: absolute; left: 18%; top: 0.65%; z-index: 999999; }
#nav-toggle { cursor: pointer; padding: 10px 35px 16px 0px; }
#nav-toggle span, #nav-toggle span:before, #nav-toggle span:after {
  cursor: pointer;
  border-radius: 1px;
  height: 2px;
  width: 18.575px;
  background: white;
  position: absolute;
  display: block;
  content: '';
}
#nav-toggle span:before {
  top: -5px; 
}
#nav-toggle span:after {
  bottom: -5px;
}

#nav-toggle span, #nav-toggle span:before, #nav-toggle span:after {
  transition: all 500ms ease-in-out;
}
#nav-toggle.active span {
  background-color: transparent;
}
#nav-toggle.active span:before, #nav-toggle.active span:after {
  top: 0;
}
#nav-toggle.active span:before {
  transform: rotate(45deg);
}
#nav-toggle.active span:after {
  transform: rotate(-45deg);
}

的javascript:

var navNav = document.getElementById( 'nav-toggle' );
var menuMenu = document.getElementById( 'menu_button' );

navToggle = function () {
    this.classList.toggle('active');
};

navNav.onclick = navToggle;

menuMenu.onclick = navToggle; // not working

jsbin:

http://jsbin.com/leqonopani/9/edit

1 个答案:

答案 0 :(得分:3)

将代码更改为:

navToggle = function () {
  navNav.classList.toggle('active');
};

当您点击#menu_button时,this会引用它,应将active类添加到#nav-toggle,以便它可以动画