<!–
button {
padding: 0;
border: none;
font: inherit;
color: inherit;
background-color: transparent;
/* show a hand cursor on hover; some argue that we
should keep the default arrow cursor for buttons */
cursor: pointer;
}
.btn {
/* default for


 

四 :active和:focus同时触发的问题!!

当我们对button进行点击时,active和focus伪类同时触发,在鼠标移开后,active伪类消失,但是focus样式还在,这种时候我们就需要点击其他地方才可以消除样式,很难受!

我们发现,有一种新的伪类:focus-visible pseudo-class (draft specification)

这个特性还没有完全确定,但是这个想法很好,是指浏览器应该只在键盘或键盘式交互之后出现:focus-visible,而鼠标点击无效。

但是由于多数浏览器还没有这个新特性,所有需要借助this polyfill.

该JS保证了后相兼容性

在引入该polyfill后

/*
  保留键盘触发的focus,取消鼠标触发的focus
*/
.js-focus-visible :focus:not(.focus-visible) {
  outline: none;
}

/*
  Optionally: Define a strong focus indicator for keyboard focus.
  If you choose to skip this step then the browser's default focus
  indicator will be displayed instead.
这段我不太清楚怎么翻译,,
*/
.js-focus-visible .focus-visible {}

在本项目中首先对hover和focus解耦

/* inverse colors on hover */
.btn:hover {
  color: #9050AA;
  border-color: currentColor;
  background-color: white;
}

/* make sure we have a visible focus ring */
.btn:focus {
  outline: none;
  box-shadow: 0 0 0 3px rgba(255, 105, 180, 0.5),
    0 0 0 1.5px rgba(255, 105, 180, 0.5);
}

然后利用polyfill完成移除多余的鼠标focus效果

/* hide focus style if not from keyboard navigation */
.js-focus-visible .btn:focus:not(.focus-visible) {
  box-shadow: none;
}

完成地址: look at the final code

只有键盘交互才会出现的focus样式!