我想知道如何在点击它之后使按钮撤消一些东西。在我的场景中只是简单的文本格式(颜色,大小等),当你第一次点击它时,它按照Javascript中的描述格式化文本,但是我想添加一个函数,当你再次点击它时,它会撤消它。
`<script>
function myFunction(){
document.getElementById("demo").style.fontsize="25px";
document.getElementById("demo").style.color="#3AF702";
document.getElementById("demo").style.backgroundcolor="red";
}
</script>`
<button type="change" onclick="myFunction()">Change!</button>
我已经检查了其他文章,这似乎是相关的,但我没有更明智地从那些,所以我提前道歉,如果它是一个副本,谢谢你的帮助!
<script>
var flag = true;
function myFunction(){
let el = document.getElementById("demo");
el.style.fontsize = flag ? "25px" : "";
el.style.color= flag ? "#3AF702" : "";
el.style.backgroundcolor=flag ? "red" : "";
flag = !flag;
}
</script>`
<button type="change" onclick="myFunction()">Change!</button>
最简单的方法是添加和删除一个类
<style>
.change {
font-size: 25px;
color: #3AF702;
background-color="red"
}
</style>
<script>
var x = 0;
function myFunction() {
if (x == 0) {
document.getElementById("demo").classList.add("change");
x = 1;
} else {
document.getElementById("demo").classList.remove("change");
x = 0;
}
}
</script>
<button type="change" onclick="myFunction()">Change!</button>
创建一个存储按钮初始值的对象和一个保存其状态的变量。
var state = 0;
var backup = {};
backup.fontSize = document.getElementById("demo").style.fontsize;
backup.color = document.getElementById("demo").style.color;
backup.background = document.getElementById("demo").style.backgroundcolor;
现在,您可以轻松地在备份和新值之间切换,如下所示:
function myFunction() {
if (state == 0) {
document.getElementById("demo").style.fontsize = "25px";
document.getElementById("demo").style.color = "#3AF702";
document.getElementById("demo").style.backgroundcolor = "red";
state = 1;
} else {
document.getElementById("demo").style.fontsize = backup.fontSize;
document.getElementById("demo").style.color = backup.color;
document.getElementById("demo").style.backgroundcolor = backup.background;
state = 0;
}
}
var flag = true;
function myFunction(){
var x = document.getElementById("demo");
if (flag) {
x.style.backgroundColor = "red";
x.style.color="#3AF702";
x.style.fontSize="25px"
} else {
x.style.backgroundColor = "blue";
x.style.color="#dddddd";
x.style.fontSize="10px"
}
flag = !flag
}
function myFunction(){
demo.className = demo.className ? "" : "style"
}
.style {
font-size: 25px;
color: red;
background: blue;
}
<p id="demo">Hi!</p>
<button type="change" onclick="myFunction()">Change!</button>