Как убрать выделение при нажатии на кнопку css

от admin

Как убрать фокус с кнопок при нажатии

У моих кнопок есть подсветка вокруг них после нажатия на них. Это находится в Chrome.

Изображение 130

Я использую Bootstrap с темой, но я уверен, что не это: я замечал это раньше в другом проекте.

Это исчезает, если я использую тег <a> вместо <button> . Зачем? Если бы я хотел использовать <button> , как бы я его убрал?

20 ответов

Я нашел эти Q и A на другой странице, и переопределение стиля фокуса кнопки сработало для меня. Эта проблема может быть специфичной для MacOS с Chrome.

Обратите внимание, что это имеет значение для доступности и не рекомендуется, пока у вас не будет хорошего согласованного состояния фокусировки для ваших кнопок и входов. В соответствии с комментариями ниже, есть пользователи, которые не могут использовать мышей.

Вам нужно что-то вроде:

Метод .blur() корректно удаляет выделение фокуса и не путает стили Bootstraps.

Не могу поверить, что никто еще не опубликовал это.

Используйте ярлык вместо кнопки.

Хотя легко просто удалить схему для всех сфокусированных кнопок (как в user1933897 answer), но это решение плохо с точки зрения доступности (например, см. Остановить передачу сообщений с помощью фонового фокуса браузера по умолчанию)

С другой стороны, вероятно, невозможно убедить ваш браузер прекратить стилизацию нажатой кнопки, если она сфокусирована, если она думает, что она сфокусировалась после нажатия на нее (я смотрю на вас, Chrome на OS X).

Итак, что мы можем сделать? Мне приходят в голову пара вариантов.

1) Javascript (jQuery): $(‘.btn’).mouseup(function() < this.blur() >)

Вы поручаете вашему браузеру удалить фокус вокруг любой кнопки сразу после, нажатие кнопки. Используя mouseup вместо click , мы сохраняем поведение по умолчанию для взаимодействий на основе клавиатуры ( mouseup не запускается клавиатурой).

Здесь вы отключите контуры для кнопок зависания. Очевидно, что это не идеально, но может быть достаточно в некоторых ситуациях.

Я понимаю, что фокус сначала применяется после события onMouseDown , поэтому вызов e.preventDefault() в onMouseDown может быть чистым решением в зависимости от ваших потребностей. Это, безусловно, удобное для доступа решение, но, очевидно, оно регулирует поведение щелчков мыши, которые могут быть несовместимы с вашим веб-проектом.

В настоящее время я использую это решение (в рамках проекта react-bootstrap ), и я не получаю фокус мерцания или удерживания фокуса кнопок после щелчка, но я все еще могу включить мой фокус и визуально визуализировать фокус те же кнопки.

Если вы используете правило :focus < outline: none; >для удаления контуров, ссылка или управление будут фокусируемыми, но без указания фокуса для пользователей клавиатуры. Способы его удаления с помощью JS, например, onfocus=»blur()» , еще хуже, и пользователь клавиатуры не сможет взаимодействовать с элементом управления.

Используемые хаки, которые вид OK, включают добавление правил :focus < outline: none; >, когда пользователи взаимодействуют с мышью и удаляют их снова, если обнаружено взаимодействие с клавиатурой. Линдсей Эванс сделал для этого lib: https://github.com/lindsayevans/outline.js

Но я бы предпочел установить класс в теге html или body. И иметь контроль в файле CSS, когда использовать это.

Например (встроенные обработчики событий предназначены только для демонстрации):

Как убрать браузерную обводку у различных элементов в состоянии :focus

Как убрать браузерную обводку у различных элементов в состоянии :focus

Верстка

В данной коротенькой статье, приведу готовое решение по тому как убрать браузерную обводку у button, input, textarea, checkbox и прочих элементов верстки появляющуюся в состоянии :focus в различных браузерах: mozilla, google chrome.

Как убрать браузерную обводку у кнопок (появляющуюся в состоянии :focus) в Chrome и Firefox?

*Аналогичная ситуация (если хотим эту браузерную обводку убрать) в случае с ссылками и инпутами решается с помощью css-стиля:

Однако в случае именно с кнопками (button) — просто применение стиля :focus не помогает.

Что делать, чтобы убрать браузерную обводку у кнопок (появляющуюся в состоянии :focus ) в Chrome и Firefox?

(*в jsfiddle при клике на кнопку в фаерфоксе — почему-то нежелательная пунктирная обводка не отображается, хотя на самом деле она есть)

How to remove focus around buttons on click

My buttons all have a highlight around them after I click them. This is in Chrome.

UnselectedSelected

I am using Bootstrap with a theme, but I’m pretty sure that’s not it: I was noticing this before on another project.

It goes away if I use an <a> tag instead of <button> . Why? If I wanted to use <button> how would I make it go away?

Читать:
Как создать геттеры и сеттеры в intellij idea

Sean Clark Hess's user avatar

46 Answers 46

I found this Q and A on another page, and overriding the button focus style worked for me. This problem may be specific to MacOS with Chrome.

Note though that this has implications for accessibility and isn’t advised until you have a good consistent focus state for your buttons and inputs. As per the comments below, there are users out there who cannot use mice.

You want something like:

The .blur() method correctly removes the focus highlighting and doesn’t mess up Bootstraps’s styles.

my understanding is that the focus is first applied following the onMouseDown event, so calling e.preventDefault() in onMouseDown may be a clean solution depending on your needs. This is certainly an accessibility friendly solution, but obviously it adjusts the behaviour of mouse clicks which may not be compatible with your web project.

I am currently using this solution (within a react-bootstrap project) and I do not receive a focus flicker or retained focus of buttons after a click, but I am still able to tab my focus and visually visualize the focus of the same buttons.

Use focus-visible

Note 1: In each of the 3 options outlined below, buttons behave the same way (no focus ring on click), but selects and inputs vary slightly in their default behavior. Only Option 3 removes focus rings consistently around buttons, inputs, and selects. Please compare all approaches and make sure you understand the implications.

Note 2: Due to the cascading nature of CSS, the order of the CSS rules is important.

Note 3: There are still some accessibility concerns with any focus-visible approach. Namely, that until browsers expose a configuration to let users choose when to show visible focus rings, focus-visible should be considered worse for accessibility than using focus rings everywhere all the time, but better than the harmful :focus approach mentioned in other answers to this question. See "A note about accessibility" section at the bottom of this answer for more details.

OPTION 1: Use the :focus-visible pseudo-class

The :focus-visible pseudo-class can be used to remove outlines and focus rings on buttons and various elements for users that are NOT navigating via keyboard (i.e., via touch or mouse click).

Warning: As of 2021, the :focus-visible pseudo-class is ** widely supported across modern browsers but fails on fringe browsers**. If old-browser support is important, the Javascript polyfill in option 2 below is the closest approximation.

OPTION 2: Use a .focus-visible polyfill

This solution uses a normal CSS class instead of the pseudo-class mentioned above and has wider browser support (in 2021). It requires either 1 or 2 Javascripts be added to your HTML; one for the official focus-visible polyfill and the other for older browsers that don’t support classList.

Note: In Chrome, the polyfill seems to treat selects differently than the native :focus-visible pseudo-class.

OPTION 3: Use a global key-navigation vs mouse-navigation state

An inverse solution to focus-visible, is to disable outlines on mousemove , and enable them on keydown -> "Tab" . In this case, rather than specifying which elements shouldn’t show an outline, you must specify which elements should.

A note about accessibility

Removing all focus rings a la :focus < outline: none; >or :focus < outline: 0; >is a known accessibility issue and is never recommended. Additionally, there are folks in the accessibility community who would rather you never remove a focus ring outline and instead make everything have a :focus style — either outline or box-shadow could be valid if styled appropriately.

Finally, some folks in the accessibility community believe developers should not implement :focus-visible on their websites until all browsers implement and expose a user preference which lets people pick whether all items should be focusable or not. I personally don’t subscribe to this thinking, which is why I provided this solution that I feel is far better than the harmful :focus < outline:none >. I think :focus-visible is a happy medium between design concerns and accessibility concerns. As of 2022, Chrome browser has exposed a user preference to set focus visibility styles, but FireFox has not.

Похожие статьи