HTML5 summary outline轮廓JS模拟outline策略实例页面

回到相关文章 »

效果:

这是示例 点击无外框,键盘focus有。

代码:

CSS代码:
summary {
    user-select: none;
    outline: 0;
}
summary[focus] {
    outline: 1px dotted;
    outline: 5px auto -webkit-focus-ring-color;
}
                
HTML代码:
<details open>
    <summary>这是示例</summary>
    <content>点击无外框,键盘focus有。</content>
</details>
                
JS代码:
window.addEventListener('keydown', function () {    
    window.isKeyEvent = true;
    setTimeout(function () {
        window.isKeyEvent = false;
    }, 100);    
});

document.addEventListener('focusin', function (event) {
    var target = event.target;
    if (target && target.tagName.toLowerCase() == 'summary' && window.isKeyEvent == true) {
        target.setAttribute('focus', '');
    }
});
document.addEventListener('focusout', function (event) {
    var eleFocusAll = document.querySelectorAll('summary[focus]');
    [].slice.call(eleFocusAll).forEach(function (summary) {
        summary.removeAttribute('focus');
    });
});