How to remove the border highlight on an input text element

前端 未结 18 1219
庸人自扰
庸人自扰 2020-11-22 05:49

When an HTML element is \'focused\' (currently selected/tabbed into), many browsers (at least Safari and Chrome) will put a blue border around it.

For the layout I a

18条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-22 06:32

    Removing all focus styles is bad for accessibility and keyboard users in general. But outlines are ugly and providing a custom focussed style for every single interactive element can be a real pain.

    So the best compromise I've found is to show the outline styles only when we detect that the user is using the keyboard to navigate. Basically, if the user presses TAB, we show the outlines and if he uses the mouse, we hide them.

    It does not stop you from writing custom focus styles for some elements but at least it provides a good default.

    This is how I do it:

    // detect keyboard users
    
    const keyboardUserCssClass = "keyboardUser";
    
    function setIsKeyboardUser(isKeyboard) {
      const { body } = document;
      if (isKeyboard) {
       body.classList.contains(keyboardUserCssClass) || body.classList.add(keyboardUserCssClass);
      } else {
       body.classList.remove(keyboardUserCssClass);
      }
    }
    
    // This is a quick hack to activate focus styles only when the user is
    // navigating with TAB key. This is the best compromise we've found to
    // keep nice design without sacrifying accessibility.
    document.addEventListener("keydown", e => {
      if (e.key === "Tab") {
       setIsKeyboardUser(true);
      }
    });
    document.addEventListener("click", e => {
      // Pressing ENTER on buttons triggers a click event with coordinates to 0
      setIsKeyboardUser(!e.screenX && !e.screenY);
    });
    
    document.addEventListener("mousedown", e => {
      setIsKeyboardUser(false);
    });
    body:not(.keyboardUser) *:focus {
      outline: none;
    }

    By default, you'll see no outline. But press TAB key and you'll see focussed element

    This is anchor link
    提交评论

提交回复
热议问题