如何解决如何将注意力集中在选定的按钮上
如何让这个焦点在点击旁边的空白字段后不消失?
<button id="button1">Text 1</button>
<button id="button2">Text 2</button>
.button1 {
height: 48px;
width: 240px;}
.button1:hover {
background-color: red;}
.button1:focus {
background-color: green;}
.button2 {
height: 48px;
width: 240px;}
.button2:hover {
background-color: red;}
.button2:focus {
background-color: green;}
解决方法
您只能通过按照以下建议设置单选框输入标签的样式,使用 HTML 和 CSS 来实现。
这种实现的优点是,如果您需要通过表单提交按钮值,则不必维护另一个元素(通过 javascript)。
span {
display: inline-block;
position: relative;
}
span > input[type=radio] {
visibility: hidden;
position: absolute;
}
span > label {
padding: 5px 10px;
border: solid 1px #ccc;
cursor: pointer;
}
span > label:hover {
background-color: #fcfcfc;
}
span > input[type=radio]:checked + label {
background-color: green;
color: white;
}
<span>
<input name="my-button" value="1" type="radio" id="my-button-1" />
<label for="my-button-1">Text 1</label>
</span>
<span>
<input name="my-button" value="2" type="radio" id="my-button-2" />
<label for="my-button-2">Text 2</label>
</span>
你可以用 Javascript 来做到这一点。
请注意,您还向按钮添加了 ids
,但在您的样式中,您的目标是 classes
。
let btns = document.querySelectorAll('button');
btns.forEach((btn)=> {
btn.addEventListener('click',function() {
if(document.querySelector('button.active')){
document.querySelector('button.active').classList.remove('active');
}
btn.classList.add('active');
});
});
#button1 {
height: 48px;
width: 240px;}
#button1:hover {
background-color: red;}
#button1:focus,#button1.active {
background-color: green;}
#button2 {
height: 48px;
width: 240px;}
#button2:hover {
background-color: red;}
#button2:focus,#button2.active {
background-color: green;}
<button id="button1">Text 1</button>
<button id="button2">Text 2</button>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。