I am trying to make the submenu open and close by class toggle
.
WHy is the class on
not toggled on click, to hide the submenu?
var u = document.querySelector('ul'); var l = u.querySelectorAll("li"); var a = u.querySelectorAll('li.hasul > a'); for(var i=0; i<a.length;i++){ a[i].addEventListener('click', function(){ l.forEach(function(i,n){ i.classList.remove('on'); }); event.target.parentNode.classList.toggle('on'); }); }
ul{display:flex; list-style:none;} li{margin:5px; position: relative; font-size: 20px; } li ul{ border: 1px solid #ccc; padding: 10px; position: absolute; left: 0; width: 150px; top: 40px; display: none; } li.on{ border-bottom: 3px solid red; } li.on ul{ display: block; } a{text-decoration:none;display:block; padding: 5px;}
<ul> <li class="hasul"><a href="#">Item 1</a> <ul> <li><a href="#">Level 2</a></li> <li><a href="#">Level 2</a></li> <li><a href="#">Level 2</a></li> </ul> </li> <li class="hasul"><a href="#">Item 2</a> <ul> <li><a href="#">Level 2</a></li> <li><a href="#">Level 2</a></li> <li><a href="#">Level 2</a></li> </ul> </li> </ul>
您应该使用touchstart
事件,而不是click
手机(检查这里)
add display:none; to the on css rule
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.