#html #css #focus
#HTML #css #фокус
Вопрос:
Я пытаюсь установить другой стиль для поля ввода, который фокусируется с помощью клавиатуры (а не с помощью мыши).
Я знаю, что с помощью мыши и клавиатуры можно различать фокус на других элементах с помощью псевдокласса :focus-visible
, но он не работает при вводе из-за спецификации:
The :focus-visible pseudo-class applies while an element matches the :focus pseudo-class and the UA determines via heuristics that the focus should be made evident on the element.
For example, UAs typically display focus indicators on text fields any time they’re focused, to draw attention to the fact that keyboard input will affect their contents.
On the other hand, UAs typically only display focus indicators on buttons when they were focused by a keyboard interaction (such as tabbing through the document)—because it’s not always immediately obvious where the focus has gone after such an interaction, but is sufficiently self-evident when the button was focused by more obviously-targetted interactions, like clicking on the button with a mouse pointer.
Есть ли какое-либо решение для отдельного стиля, когда поле ввода фокусируется с помощью мыши или клавиатуры?
Ответ №1:
Вы можете добавить дополнительные стили для :hover
в дополнение к :focus-visible
или :focus
, если это работает для вас. Пример здесь (https://codepen.io/alekskorovin/pen/OJxJaQB ):
input {
outline: 4px dashed transparent;
}
input:focus-visible {
outline: 4px dashed darkorange;
}
input:hover:focus-visible {
outline: 4px dashed darkgreen;
}
input:hover {
outline: 4px dashed transparent;
}
<input type="text" />
Комментарии:
1. Хорошая попытка, но мне нужно лучшее решение, которое всегда будет работать. Не только тогда, когда пользователь оставит мышь на поле ввода.