You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为dropdown-arrow添加同步下拉菜单切换功能失败的技术咨询

解决下拉菜单箭头点击无响应的问题

问题根源

点击箭头时,myFunction确实会触发菜单切换,但随后window.onclick事件检测到点击目标不是#verify-name,立刻关闭菜单,导致视觉上没效果;同时箭头元素还未绑定点击事件。

修复步骤

  1. 给箭头元素添加onclick事件绑定
  2. 修改window.onclick的判断逻辑,将箭头元素加入不触发关闭的白名单
  3. 在myFunction中阻止事件冒泡,避免点击触发元素后事件传递到window引发冲突

修改后的完整代码

HTML

<div class="buttons">
    <div>
        <a id="verify-name" onclick="myFunction(event)">Press Me</a>
        <img id="dropdown-arrow" onclick="myFunction(event)" src="https://www.svgrepo.com/show/335062/dropdown.svg">

        <div class="dropdown-content">
            <span>Logout</span>
        </div>
    </div>
</div>

JavaScript

function myFunction(event) {
    event.stopPropagation(); // 阻止事件冒泡到window
    document.getElementsByClassName('dropdown-content')[0].classList.toggle('show');
}
// Close dropdown if the user clicks on window
window.onclick = function(event) {
    // 排除Press Me和箭头元素
    if (!event.target.matches('#verify-name') && !event.target.matches('#dropdown-arrow')) {
        var dropdowns = document.getElementsByClassName('dropdown-content');
        var i;
        for (i = 0; i < dropdowns.length; i++) {
            var openDropdown = dropdowns[i];
            if (openDropdown.classList.contains('show')) {
                openDropdown.classList.remove('show');
            }
        }
    }
}

CSS(保持原有代码即可)

.buttons {
    display: flex;
    position: relative;
}
#dropdown-arrow {
    height: 20px;
}
.dropdown-content {
    display: none;
    position: absolute;
        padding: 14px; background-color: yellow;
}
.show {
    display: flex;
}

内容的提问来源于stack exchange,提问作者Sabrina

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 16:23:23