Javascript设置按钮处于活动状态

时间:2020-10-20 08:47:09

标签: javascript html css

我有一个按钮表,填充后,我正在使用

document.getElementById("btn0").click();

单击第一个按钮。该按钮正在执行应做的操作,但是按钮的背景颜色没有像我手动单击时一样改变。

如您所见,它运行时,div的背景颜色正在变化,但是该按钮未设置为活动状态。

代码段:

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>

这是我创建的jsfiddle的链接: https://jsfiddle.net/58hrwcgo/3/

4 个答案:

答案 0 :(得分:2)

There's a difference between click and focus.

click()单击元素,然后取消聚焦,这与真正的鼠标单击不同,后者先单击然后聚焦。

我建议同时执行以下操作来模拟真实点击:

document.getElementById("btn0").click();
document.getElementById("btn0").focus();

答案 1 :(得分:1)

js

const btn = document.getElementById("btn0")
var myfunc = function(){
    document.getElementById("test").style.backgroundColor="red";
    btn.focus();
};

btn.click();

css

...

.btn:active, .btn.active{
  background-color:green;
  outline: none;
}

...

答案 2 :(得分:1)

手动单击时,首先触发焦点状态ist。这就是外观根据您的课程.btn:focus而变化的原因。

document.getElementById("btn0").focus();
document.getElementById("btn0").click();

将导致所需的行为。

此外,您在{-{1}}状态下的CSS示例中缺少冒号:

:active

答案 3 :(得分:0)

您可以尝试HTML DOM focus()方法。

 document.getElementById("btn0").focus(); 

您可以在here中了解有关此内容的更多信息。