JavaScript上下箭头菜单(仅Javascript)

时间:2018-10-11 08:59:48

标签: javascript drop-down-menu

JavaScript向上和向下箭头菜单

我在这里发布我的代码,我想为菜单创建一些JavaScript箭头,该菜单需要向上和向下的功能,所以我试图找出它仅存在于jquery中,我到处搜索有很多令人困惑的代码。但是我只需要一个简单而纯净的javascript代码。请有人愿意帮助我。

var menuup = document.getElementsByClassName("btn-down");
var menudwn = document.getElementsByClassName('btn-open');
nav {
  position: relative;
  padding: 45px 0px 0px 180px;
  width: 1rem;
}

nav ul {
  list-style: none;
  margin: 0;
  padding: 0;
}

nav>ul>li {
  float: left;
  background: blue;
}

nav ul::after {
  content: '';
  display: block;
  clear: both;
}

nav ul li:hover>ul {
  display: block;
}

nav ul li a {
  display: inline-block;
  color: #fff;
  padding: 0.9rem 1rem;
  text-decoration: none;
  width: 120px;
}

nav ul li a:hover {
  background-color: #339999;
}

.btn-open:after {
  font-family: "FontAwesome";
  content: "\f0de";
  color: #fff;
  font-size: 22px;
}

.btn-down:after {
  font-family: "FontAwesome";
  content: "\f0dd";
  color: #fff;
  font-size: 22px;
  position: relative;
  left: 10px;
}
 <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet"/>
 <nav>  
     <ul>
          <li><a href="#" class="btn-down">About us</a></li>                                           
      </ul>
 </nav>

1 个答案:

答案 0 :(得分:0)

这是您想要的吗?

var anchors = Array.from(document.querySelectorAll('a'));

anchors.map(anchor => {
	if(anchor.classList.contains('btn-open') || anchor.classList.contains('btn-down')) {
    anchor.addEventListener('click', () => {
      if(anchor.classList.contains('btn-open')) {
        anchor.classList.remove('btn-open');
        anchor.classList.add('btn-down');
      } else {
        anchor.classList.add('btn-open');
        anchor.classList.remove('btn-down');
      } 
    });
  }
});
nav {
  position: relative;
  padding: 45px 0px 0px 180px;
  width: 1rem;
}

nav ul {
  list-style: none;
  margin: 0;
  padding: 0;
}

nav>ul>li {
  float: left;
  background: blue;
}

nav ul::after {
  content: '';
  display: block;
  clear: both;
}

nav ul li:hover>ul {
  display: block;
}

nav ul li a {
  display: inline-block;
  color: #fff;
  padding: 0.9rem 1rem;
  text-decoration: none;
  width: 120px;
}

nav ul li a:hover {
  background-color: #339999;
}

.btn-open:after {
  font-family: "FontAwesome";
  content: "\f0de";
  color: #fff;
  font-size: 22px;
  position: relative;
  left: 10px;
  top: 8px;
}

.btn-down:after {
  font-family: "FontAwesome";
  content: "\f0dd";
  color: #fff;
  font-size: 22px;
  position: relative;
  left: 10px;
  top: -2px;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet" />

<nav>
  <ul>
    <li><a href="#" class="btn-down">About us</a></li>
     <li><a href="#" class="btn-down">Products</a></li>
  </ul>
</nav>