如何将注意力集中在选定的按钮上

问题描述

页面上有两个按钮,当你点击其中一个按钮时,它会改变颜色。

如何让这个焦点在点击旁边的空白字段后不消失?

<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>

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...