在这件事上需要您的帮助。在导航栏中,我有一个名为作者的项目,单击时以下拉列表的形式显示有关作者的信息。问题是下拉菜单是可点击的,这使得它消失。我希望能够仅在导航栏中显示/关闭它。
<div id = 'Author' class = 'navbarItem'>Author
<div id = 'authorInfo'>
// info about author
</div>
const author = document.getElementById('Author');
const authorInfo = document.getElementById('authorInfo');
author.onclick = () => {
if(authorInfo.style.display == 'none' || authorInfo.style.display == '')
authorInfo.style.display = 'block'
else
authorInfo.style.display = 'none';
}
尝试过将authorInfo的onclick事件设置为null,但不起作用。
最佳答案
在监听器上添加事件参数,以测试是否在容器上而不是其子容器上进行了单击。 event.target
保存被单击的元素。
const author = document.getElementById('Author');
const authorInfo = document.getElementById('authorInfo');
// You need the event parameter on function
author.onclick = function(event) {
// Do it only if clicked element is author div, not its child
if(event.target == author) {
if(authorInfo.style.display == 'none' || authorInfo.style.display == '')
authorInfo.style.display = 'block'
else
authorInfo.style.display = 'none';
}
}
<div id = 'Author' class = 'navbarItem'>Author
<div id = 'authorInfo' style="display:none;">
// info about author
</div>
</div>
关于javascript - 如何去掉子元素的点击事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61194415/