微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

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

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

<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 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?