gpt4 book ai didi

javascript - 如何以编程方式关注没有轮廓的 HTML 元素?

转载 作者:可可西里 更新时间:2023-11-01 13:48:13 25 4
gpt4 key购买 nike

注意::focus { outline: none } 不应该是答案,因为它在按 tab 键导航时也会阻止 outline

单击按钮不显示轮廓,但按钮变为 document.activeElement ( JSFiddle )。我想模仿这种行为无需点击鼠标

enter image description here

方法应该:

  1. 将元素设为document.activeElement
  2. 不引起大纲
  3. 按键盘 Tab 键时仍然允许轮廓

(如果有人问,我目前的意图是聚焦模态对话框并在对话框关闭时将焦点返回到先前聚焦的元素。这需要防止轮廓以获得无缝体验。)

伪代码:

showDialog();

function whenDialogClosed() {
previouslyFocused.focus(); // should not display outline
}

最佳答案

CSS 最后 got an answer通过添加伪类 :focus-visible恰好在 browser decides to do 时激活.

For this reason, modern browsers apply simple heuristics to determine whether or not to apply their default focus styling. In general, if an element received focus as a result of a mouse/pointer click, browsers will suppress their default focus indication.

截至 2021 年,all modern browsers support this ,但是如果您需要支持旧版浏览器,请使用 a polyfill并这样做:

/*
* .js-focus-visible is automatically added to document.body
* to ensure the rules run only in JS-supported environment
*/

.js-focus-visible .your-selector:focus:not(.focus-visible) { outline: none }

演示:

focusrandom.addEventListener("click", () => {
const num = Math.ceil(Math.random() * 5);
const button = document.getElementById(`button${num}`);
button.focus();
});
wofocusrandom.addEventListener("click", () => {
const num = Math.ceil(Math.random() * 5);
const button = document.getElementById(`wobutton${num}`);
button.focus();
});
.js-focus-visible .apply button:focus:not(.focus-visible) {
outline: none;
}
<script src="https://unpkg.com/focus-visible"></script>
<p class="apply">
With focus-visible:
<button id="button1">1</button>
<button id="button2">2</button>
<button id="button3">3</button>
<button id="button4">4</button>
<button id="button5">5</button>
</p>
<p>
Without focus-visible:
<button id="wobutton1">1</button>
<button id="wobutton2">2</button>
<button id="wobutton3">3</button>
<button id="wobutton4">4</button>
<button id="wobutton5">5</button>
</p>

<button id="focusrandom">Focus random button</button>
<button id="wofocusrandom">Focus random button without focus-visible</button>

(来自 https://stackoverflow.com/a/50571098/2460034。谢谢亚伦!)

关于javascript - 如何以编程方式关注没有轮廓的 HTML 元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38987240/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com