html - JavaScript:使用按钮更改文本颜色,每次点击按钮时应显示不同的样式。不能正常工作
我对 JavaScript 还比较新。我刚写了这个简单的脚本:
[HTML 代码]
<html>
<body>
<script src="externalscript.js"></script>
<p id="text">This text will change style</p><br>
<button type="button" onclick="changeStyle()">Click me</button>
</body>
</html>
[JS 代码]
function changeStyle() {
status = 1;
x = document.GetElementById("text");
if(status==1) {
x.style.color = 'blue';
status = 2;
}
if(status==2) {
x.style.color = 'red';
status = 3;
}
if(status==3) {
x.style.color = 'yellow';
status = 1;
}
}
我希望每次点击按钮时,它都能将文本更改为不同的样式。然而,这并没有生效。有人能解释一下如何正确做到这一点吗?
答案#1
试试这个:
status = 1;
function changeStyle() {
//Note the lowercase first letter.
x = document.getElementById("text");
if(status==1) {
x.style.background-color = 'blue';
status = 2;
}
else if(status==2) {
x.style.background-color = 'red';
status = 3;
}
else if(status==3) {
x.style.background-color = 'yellow';
status = 1;
}
}
你需要使用 'else if',因为否则浏览器在改变颜色后,会立即进入下一个 if 块,并认为“好吧,现在是真的”,然后执行那个代码,一直执行到你当前代码的结尾。使用 'else if' 可以告诉浏览器一旦第一个 if 块被评估,就忽略其他的 if 块。
希望这能帮到你。
答案#2
它是
getElementById("text")
不
GetElementById("text");
另外,如果我理解你想要实现的目标,你应该将 status=1; 放在函数外面。将它声明为全局变量,这样你就可以在每个 if 语句内部修改它。
你还必须使用 else_if 而不是 if
演示
