当单击给定的Id时,使用Javascript添加一个新类



给定HTML

<button id="showanswer">Show Answer</button>

当点击"This Frist Time Than add Class"时;一个";AND当返回点击它删除类";一个";

如何使用javascript

#showanswer {
display: inline-block;
line-height: 20px;
padding: 2px 5px 2px 25px;
color: #fff;
border: none;
font-size: 13px;
color: #fff;
background-color: #1bbc9b;
}
<button id="showanswer">Show Answer</button>

您可以切换类:

document.getElementById("showanswer").addEventListener("click", function(e){
e.target.classList.toggle("one");
});
#showanswer {
display: inline-block;
background: url(https://static.javatpoint.com/images/eye-black.png) 1px 1px no-repeat;
line-height: 20px;
padding: 2px 5px 2px 25px;
margin: 0 0 10px 0!important;
border: none;
font-size: 13px;
color: #fff;
border: none;
font-size: 13px;
color: #fff;
background-color: #1bbc9b;
}
<button id="showanswer">Show Answer</button>

例如,您可以使用document.querySelectordocument.getElementById在JavaScript中选择特定元素,然后添加以下内容:

const showAnswerBtn = document.getElementById("showanswer");
showAnswerBtn.classList.toggle('one');

最新更新