Javascript设置按钮处于活动状态



我有一个按钮表,一旦填充好,我就使用

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/

clickfocus之间存在差异。

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

我建议通过同时执行以下操作来模拟真正的点击:

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

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

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

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

将导致所需的行为。

此外,在:active状态下的CSS示例中缺少一个冒号:

.btn:active, .btn.active { ... }

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

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

你可以在这里阅读更多关于这方面的信息。

方法1:

您可以使用querySelector函数选择按钮,然后添加"活动的";到其类别列表。您还需要更改活动按钮的css选择

var myfunc = function(){
document.getElementById("test").style.backgroundColor="red";
// add the following changes
const btn = document.querySelector(".btn")
btn.classList.add('active');
};
document.getElementById("btn0").click();
/*  ....
/*  change the btn active to the following */
.btn.active{
background-color:green;
outline: none;
}

/* .....

方法2:使用addEventListener(首选(

您可以在JavaScript中完成整个过程,而无需使用";onclick";在HTML 中

const test =  document.querySelector("#test")
const btn = document.querySelector(".btn")
btn.addEventListener('click', ()=>{
test.style.backgroundColor="red";
btn.classList.add('active');
});
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;
}
/*  change the btn active to the following */
.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" id="btn0"> Cool button</button>
<div id="test">
Hello
</div>

最新更新