- :focus
- Пример
- Как пишется
- Как понять
- Подсказки
- На практике
- Алёна Батицкая советует
- HTMLElement: focus() method
- Syntax
- Parameters
- Return value
- Examples
- Focus on a text field
- HTML
- JavaScript
- Result
- Focus on a button
- HTML
- JavaScript
- Result
- Focus with and without scrolling
- HTML
- JavaScript
- Result
- Specifications
- Notes
- Browser compatibility
- See also
- Found a content problem with this page?
:focus
Сайтом можно пользоваться не только с использованием мышки, но и при помощи клавиатуры. При переключении клавишей Tab элементу добавляется псевдокласс :focus , и мы можем задать для него красивые стили.
Элементы формы могут получить фокус и при клике мышкой на него. Например, если кликнуть по кнопке или в поле ввода текста, то им будет добавлен псевдокласс :focus .
Важно! В браузерах Safari и Firefox на Mac при клике мышкой на кнопку фокус не устанавливается.
Пример
Скопировать ссылку «Пример» Скопировано
При попадании фокуса на кнопку будем показывать заметную белую обводку:
button:focus outline: 2px solid #ffffff; outline-offset: 3px;>
button:focus outline: 2px solid #ffffff; outline-offset: 3px; >
Как пишется
Скопировать ссылку «Как пишется» Скопировано
После любого селектора ставим двоеточие и пишем ключевое слово focus .
a:focus outline: 2px solid hotpink;>
a:focus outline: 2px solid hotpink; >
Как понять
Скопировать ссылку «Как понять» Скопировано
При попадании элемента в фокус браузер подставляет элементу дополнительный автоматический класс, чтобы пометить изменение состояния. Этому классу мы можем задавать любые стили, подходящие по дизайну. При этом логика подставления или удаления этого класса скрыта под капотом движка браузера.
Важно знать, что в стандартных стилях браузера уже прописаны дефолтные стили для фокуса интерактивных элементов. Например, в Google Chrome вокруг элемента появляется прямоугольная фиолетовая рамка. Стили для неё:
:focus outline: -webkit-focus-ring-color auto 1px;>
:focus outline: -webkit-focus-ring-color auto 1px; >
Важно! Не удаляйте стили для фокуса полностью. Если вам не нравятся дефолтные стили — измените их. При полном удалении фокуса пользователь не будет понимать, в какой части страницы он находится, если его сценарий пользования сайтом отличается от привычного.
Подсказки
Скопировать ссылку «Подсказки» Скопировано
💡 Смену стилей между состояниями можно анимировать при помощи transition 🎉
💡 В браузер встроены дефолтные стили для фокуса.
💡 Нельзя полностью удалять стили для фокуса, заменяйте их на свои, если дефолтные не нравятся.
💡 Стили для фокуса можно увидеть, открыв сайт и несколько раз нажав клавишу Tab . Или нажмите на кнопку, поставьте курсор в поле ввода.
На практике
Скопировать ссылку «На практике» Скопировано
Алёна Батицкая советует
Скопировать ссылку «Алёна Батицкая советует» Скопировано
🛠 В какой-то момент разработчики так разозлились на обводку, появляющуюся при фокусе, что начали её полностью убирать, переопределяя стандартные стили. Какое-то время это было очень распространено, но довольно быстро пришло осознание, что тем самым мы портим опыт пользования интернетом — как минимум, некоторым людям. Например, на момент написания этой статьи на сайте «Алиэкспресс» отключена обводка на интерактивных элементах. И если вы попробуете походить по сайту, используя клавиатуру, то не сможете понять, где находится ваш курсор в данный момент.
Не стоит думать, что абсолютно все, кто попадает в интернет, используют мышку для навигации. Есть люди с временно или постоянно ограниченными возможностями, которым гораздо комфортнее использовать для навигации по сайту клавиатуру. И они должны видеть, где именно в данный момент находится курсор.
Мы — разработчики — как создатели сайтов должны помнить, что пользовательские сценарии могут быть совершенно разные, и мы не в праве обделять ни одного из наших пользователей.
Если дизайнер не прорисовал в макете стили для фокуса, то вы можете оставить стандартные стили или аккуратно подобрать что-то подходящее под дизайн сайта.
HTMLElement: focus() method
The HTMLElement.focus() method sets focus on the specified element, if it can be focused. The focused element is the element that will receive keyboard and similar events by default.
By default the browser will scroll the element into view after focusing it, and it may also provide visible indication of the focused element (typically by displaying a «focus ring» around the element). Parameter options are provided to disable the default scrolling and force visible indication on elements.
Syntax
Parameters
An optional object for controlling aspects of the focusing process. This object may contain the following properties:
A boolean value indicating whether or not the browser should scroll the document to bring the newly-focused element into view. A value of false for preventScroll (the default) means that the browser will scroll the element into view after focusing it. If preventScroll is set to true , no scrolling will occur.
focusVisible Optional Experimental
A boolean value that should be set to true to force visible indication that the element is focused. By default, or if the property is not true , a browser may still provide visible indication if it determines that this would improve accessibility for users.
Return value
Examples
Focus on a text field
This example uses a button to set the focus on a text field.
HTML
input id="myTextField" value="Text field." /> button id="focusButton">Click to set focus on the text fieldbutton>
JavaScript
The code below adds an event handler to set the focus on the text field when the button is pressed. Note that most browsers will automatically add visible indication (a «focus ring») for a focused text field, so the code does not set focusVisible to true .
.getElementById("focusButton").addEventListener("click", () => document.getElementById("myTextField").focus(); >);
Result
Select the button to set focus on the text field.
Focus on a button
This example demonstrates how you can set the focus on a button element.
HTML
First we define three buttons. Both the middle and right button will set focus on the left-most button. The right right-most button will also specify focusVisible .
button id="myButton">Buttonbutton> button id="focusButton">Click to set focus on "Button"button> button id="focusButtonVisibleIndication"> Click to set focus and focusVisible on "Button" button>
JavaScript
The code below sets up handlers for click events on the middle and right buttons.
.getElementById("focusButton").addEventListener("click", () => document.getElementById("myButton").focus(); >); document .getElementById("focusButtonVisibleIndication") .addEventListener("click", () => document.getElementById("myButton").focus( focusVisible: true >); >);
Result
Select either the middle button or right-most button to set focus on the left-most button.
Browsers do not usually show visible focus indication on button elements when focus is set programmatically, so the effect of selecting the middle button may not be obvious. However provided the focusVisible option is supported on your browser, you should see focus changing on the left-most button when the right-most button is selected.
Focus with and without scrolling
This example shows the effect of setting focus with the option preventScroll set true and false (the default).
HTML
The HTML defines two buttons that will be used to set the focus of a third button that is off-screen
button id="focus_scroll">Click to set focus on off-screen buttonbutton> button id="focus_no_scroll"> Click to set focus on offscreen button without scrolling button> div id="container"> button id="myButton" style="margin-top: 500px;">Buttonbutton> div>
JavaScript
This code sets a click event handler on the first and second buttons to set the focus on the last button. Note that the first handler doesn’t specify the preventScroll option so scrolling to the focused element will be enabled.
.getElementById("focus_scroll").addEventListener("click", () => document.getElementById("myButton").focus(); // default: >); document.getElementById("focus_no_scroll").addEventListener("click", () => document.getElementById("myButton").focus( preventScroll: true >); >);
Result
Select the first button to set focus and scroll to the off-screen button. Selecting the second button set’s the focus, but scrolling is disabled.
Specifications
Notes
- If you call HTMLElement.focus() from a mousedown event handler, you must call event.preventDefault() to keep the focus from leaving the HTMLElement
- Behavior of the focus in relation to different HTML features like tabindex or shadow dom, which previously remained under-specified, were updated in October 2019. See the WHATWG blog for more information.
Browser compatibility
BCD tables only load in the browser
See also
Found a content problem with this page?
This page was last modified on Apr 7, 2023 by MDN contributors.
Your blueprint for a better internet.