[英]Javascript set button active
I have a table of buttons and once it is populated, I am using我有一个按钮表,一旦它被填充,我就会使用
document.getElementById("btn0").click();
to click the first button.单击第一个按钮。 The button is doing what it should do, but the background color of the button is not changing the same way it does when I am clicking it manually.
该按钮正在做它应该做的事情,但是按钮的背景颜色并没有像我手动单击它时那样改变。
As you can see when its running, the background-color of the div is changing, but the button is not set to active.正如您在运行时所看到的,div 的背景颜色正在发生变化,但按钮未设置为活动状态。
Code Snippet:代码片段:
var myfunc = function(){ document.getElementById("test").style.backgroundColor="red"; }; document.getElementById("btn0").click();
.btn{ border: none; color: white; width: 100%; padding: 5px 5px 5px 5px; height: 50px; cursor: pointer; font-size: 12px; background-color: #343a40; } .btn:active .btn.active{ background-color:green; outline: none; } .btn:focus{ background-color:green; outline: none; } #test{ background-color: green; width: 600px; height: 400px; }
<button class="btn" onclick="myfunc()" id="btn0"> Cool button</button> <div id="test"> Hello </div>
Here is a link to a jsfiddle I created: https://jsfiddle.net/58hrwcgo/3/这是我创建的 jsfiddle 的链接: https ://jsfiddle.net/58hrwcgo/3/
There's a difference between click
and focus
. click
和focus
是有区别的。
click()
clicks on the element and then unfocuses, unlike a real mouse click, which clicks and then focuses. click()
点击元素然后不聚焦,不像真正的鼠标点击,点击然后聚焦。
I would recommend simulating a real click by doing both:我建议通过同时执行以下两项操作来模拟真正的点击:
document.getElementById("btn0").click();
document.getElementById("btn0").focus();
const btn = document.getElementById("btn0")
var myfunc = function(){
document.getElementById("test").style.backgroundColor="red";
btn.focus();
};
btn.click();
...
.btn:active, .btn.active{
background-color:green;
outline: none;
}
...
When clicking manually a focus state ist triggered first.手动单击时,首先触发焦点状态。 That's why the appearance changes according to your class
.btn:focus
.这就是为什么外观会根据您的班级
.btn:focus
发生变化的原因。
document.getElementById("btn0").focus();
document.getElementById("btn0").click();
will lead to the desired behavior.将导致所需的行为。
Furthermore you're missing a colon in your CSS-Example within the :active
state:此外,您在
:active
状态下的 CSS 示例中缺少一个冒号:
.btn:active, .btn.active { ... }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.