How to remove the border highlight on an input tex

2018-12-31 19:50发布

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

For the layout I am working on, this is distracting and does not look right.

<input type="text" name="user" class="middle" id="user" tabindex="1" />

FireFox does not seem to do this, or at least, will let me control it with

border: x;

If someone can tell me how IE performs, I would be curious.

But getting Safari to remove this little bit of flare would be nice.

14条回答
姐姐魅力值爆表
2楼-- · 2018-12-31 20:17

I tried all the answers and I still couldn't get mine to work on Mobile, until I found -webkit-tap-highlight-color.

So, what worked for me is...

* { -webkit-tap-highlight-color: transparent; }
查看更多
查无此人
3楼-- · 2018-12-31 20:19

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;
}
<p>By default, you'll see no outline. But press TAB key and you'll see focussed element</p>
<button>This is a button</button>
<a href="#">This is anchor link</a>
<input type="checkbox" />
<textarea>textarea</textarea>
<select/>

查看更多
登录 后发表回答