我在屏幕右上角有两个语言选择器,如 EN | FR。当用户单击 EN 时,EN 文本的颜色和文本装饰应该改变。当用户单击 FR 时,文本装饰和颜色以及 EN 应该恢复到其原始颜色和文本装饰。功能应该切换.
有什么方法可以仅使用 HTML 和 CSS 实现它吗?
最佳答案
一种选择是使用 :focus
对包含 EN
/FR
的元素进行伪类。在这种情况下,元素应该具有接收焦点的能力。一种可能的解决方案是为该元素提供一个 tabindex
属性:
span {
display: inline-block;
padding: .5rem;
background: gold;
outline: 0;
cursor: pointer;
}
span:focus {
background-color: tomato;
color: white;
}
<span tabindex="-1">EN</span>
<span tabindex="-1">FR</span>
请注意,只要用户没有点击页面上的其他地方,就会应用 :focus
。
另外值得注意的是,:focus
在旧版网络浏览器中得到了很好的支持。
另一种选择是将单选按钮 hack 与 :checked
一起使用切换样式的伪类:
label {
display: inline-block;
padding: .5rem;
background: gold;
cursor: pointer;
}
input[id^="lang_"] {
display: none;
}
input[id^="lang_"]:checked + label {
background-color: tomato;
color: white;
}
<input type="radio" id="lang_en" name="language">
<label for="lang_en">EN</label>
<input type="radio" id="lang_fr" name="language">
<label for="lang_fr">FR</label>
:checked
IE9+支持伪类
关于html - 如何使用CSS在两个文本之间切换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30044079/