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

如何修复带onfocusout事件的按钮:点击显示链接不被隐藏?

解决按钮onfocusout导致链接无法点击的问题

问题分析

点击"Look Down"按钮后链接会显示,但点击链接时,按钮失去焦点触发onfocusout事件,调用start()函数直接隐藏链接,导致链接的跳转事件还未触发就被隐藏,无法正常跳转。

解决方案

方案1:移除按钮的onfocusout事件(最简单)

如果仅需要通过按钮点击切换链接的显示/隐藏,直接移除onfocusout属性即可:

修改后的HTML:

<!DOCTYPE html>
<html>
    <head>
        <script src="script.js"></script>
    </head>
    <body style="color: black;">
        <button id="button" onclick="start()">Look Down</button>
        <table>
            <tr>
                <td>
                    <a style="display: none;" id="list" href="https://google.com/">Player-1</a>
                </td>
            </tr>
        </table>
    </body>
</html>

简化后的script.js:

function start(){
    const link = document.getElementById("list");
    link.style.display = link.style.display === "none" ? "block" : "none";
}

方案2:判断焦点转移目标,跳过隐藏逻辑

如果需要保留"点击其他区域隐藏链接"的功能,但要允许点击链接跳转,可以通过事件对象的relatedTarget判断焦点是否转移到链接上,跳过隐藏操作:

修改后的HTML(传递事件对象):

<!DOCTYPE html>
<html>
    <head>
        <script src="script.js"></script>
    </head>
    <body style="color: black;">
        <button id="button" onclick="start(event)" onfocusout="start(event)">Look Down</button>
        <table>
            <tr>
                <td>
                    <a style="display: none;" id="list" href="https://google.com/">Player-1</a>
                </td>
            </tr>
        </table>
    </body>
</html>

对应的script.js:

function start(event){
    const link = document.getElementById("list");
    
    // 若为onfocusout触发且焦点转移到链接上,不执行隐藏
    if(event.type === "focusout" && event.relatedTarget === link){
        return;
    }
    
    link.style.display = link.style.display === "none" ? "block" : "none";
}

方案3:延迟执行隐藏操作

通过setTimeout延迟隐藏链接,确保链接的跳转事件优先触发:

修改后的script.js:

function start(){
    const link = document.getElementById("list");
    
    if(link.style.display === "none"){
        link.style.display = "block";
    } else {
        // 延迟100ms执行隐藏,给跳转事件留执行时间
        setTimeout(() => {
            link.style.display = "none";
        }, 100);
    }
}

适用场景说明

  • 方案1:适合仅需按钮控制链接显示/隐藏的场景,代码最简洁;
  • 方案2:适合需要点击页面其他区域隐藏链接,但允许点击链接跳转的场景,逻辑更精准;
  • 方案3:适合快速修复现有代码,无需大幅调整的临时场景。

内容的提问来源于stack exchange,提问作者M.Riyan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 13:17:48