简体   繁体   English

如何将焦点保持在选定的按钮上

[英]How to keep focus on a selected button

there are two buttons on the page, when you click on one, it changes color.页面上有两个按钮,当您单击一个时,它会改变颜色。

How to make this focus not disappear after clicking on the empty field next to it?单击旁边的空白字段后如何使该焦点不消失?

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

You can do it with HTML and CSS only by styling the labels of radio inputs as the following suggestion.您可以使用 HTML 和 CSS 仅通过按照以下建议设置无线电输入标签的样式来做到这一点。

The advantage of this implementation is that you don't have to maintain another element (by javascript) if you need the button value to be submitted through a form.这种实现的优点是,如果您需要通过表单提交按钮值,则不必维护另一个元素(通过 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>

You could do so with Javascript.您可以使用 Javascript 来执行此操作。 Note that you are also adding ids to your buttons but in your styles you are targeting classes .请注意,您还向按钮添加了ids ,但在 styles 中,您的目标是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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM