如何使用 React 的样式组件将按钮集中在单击上?
How can I focus a button on click with styled-components for React?
我想做一件简单的事情:点击我的按钮时会改变背景颜色。
我正在使用样式组件,而伪类 :focus
:visited
:target
不起作用。我还尝试将我的 div
更改为锚点 link。
奇怪的是,:hover
确实有效,但上面提到的那些无效。
const Box = styled.div`
display: flex;
justify-content: center;
align-items: center;
padding: 18px;
box-shadow: 0 5px 5px rgba(17, 16, 62, 0.1);
font-size: 16px;
font-weight: 700;
border: 2px solid rgb(74, 165, 234);
border-radius: 3px;
background: white;
cursor: pointer;
&:hover {
box-shadow: 0 5px 5px rgba(17, 16, 62, 0.15);
}
&:focus {
background: rgb(104, 173, 226);
color: white;
}`
我希望按钮在单击后会更改背景颜色。但它什么都不做。
Div 不可聚焦。要么使用实际的 <button>
(当然是 styled.button
),要么给它一个 tabindex:
div,
button {
padding: 0.5em;
border: 1px solid hotpink;
width: 50%;
font-size: 1rem;
}
div:focus,
button:focus {
background: hotpink;
}
<div>div without tabindex</div>
<button>button</button>
<div tabindex="0">div with tabindex</div>
可聚焦 HTML 个元素:https://gist.github.com/jamiewilson/c3043f8c818b6b0ccffd
Tabindex 值:https://snook.ca/archives/accessibility_and_usability/elements_focusable_with_tabindex
我想做一件简单的事情:点击我的按钮时会改变背景颜色。
我正在使用样式组件,而伪类 :focus
:visited
:target
不起作用。我还尝试将我的 div
更改为锚点 link。
奇怪的是,:hover
确实有效,但上面提到的那些无效。
const Box = styled.div`
display: flex;
justify-content: center;
align-items: center;
padding: 18px;
box-shadow: 0 5px 5px rgba(17, 16, 62, 0.1);
font-size: 16px;
font-weight: 700;
border: 2px solid rgb(74, 165, 234);
border-radius: 3px;
background: white;
cursor: pointer;
&:hover {
box-shadow: 0 5px 5px rgba(17, 16, 62, 0.15);
}
&:focus {
background: rgb(104, 173, 226);
color: white;
}`
我希望按钮在单击后会更改背景颜色。但它什么都不做。
Div 不可聚焦。要么使用实际的 <button>
(当然是 styled.button
),要么给它一个 tabindex:
div,
button {
padding: 0.5em;
border: 1px solid hotpink;
width: 50%;
font-size: 1rem;
}
div:focus,
button:focus {
background: hotpink;
}
<div>div without tabindex</div>
<button>button</button>
<div tabindex="0">div with tabindex</div>
可聚焦 HTML 个元素:https://gist.github.com/jamiewilson/c3043f8c818b6b0ccffd
Tabindex 值:https://snook.ca/archives/accessibility_and_usability/elements_focusable_with_tabindex