我想使用HTML,CSS和JavaScript在网页上创建经典菜单栏。一切正常,但是单击菜单项不会隐藏菜单。而是出现菜单,直到光标移出该项目为止。这是不自然的,在基于触摸的设备上尤其麻烦。在线解决方案都使用jQuery,它对我来说并不陌生。有没有一种方法可以在不使用jQuery的情况下隐藏菜单?
function onButtonClick(event) {
event.stopPropagation();
console.log(event.target.id);
//close menu here
}
答案 0 :(得分:1)
首先,您指定要处理的元素:
var el = this.parentNode;
然后,使用与CSS相同的逻辑,将display
设置为none
。
el.style.display = "none";
最后,在30ms
之后,您可以还原内联样式以保留hover
的效果:
setTimeout(function() {
el.style.removeProperty("display");
}, 30);
最终结果将是这样:
function onButtonClick(event) {
event.stopPropagation();
console.log(event.target.id);
var el = this.parentNode;
el.style.display = "none";
setTimeout(function() {
el.style.removeProperty("display");
}, 30);
}
希望有帮助。
答案 1 :(得分:0)
处理点击事件的另一种方法:
HTML:
<li class="dropdown" id="file" onclick="onClick(this)">
...
</li>
<li class="dropdown" id="view" onclick="onClick(this)">
...
</li>
CSS:
/*.dropdown:hover .dropdown-content {
display: block;
}*/
和JavaScript:
function onClick(event) {
let list = event.children;
setDisplayProperty(list);
}
function setDisplayProperty(list) {
for (let item of list) {
console.log(item.id);
if(item.style.display == 'block')
item.style.display = '';
else
item.style.display = 'block';
}
}