我创建了一个抽认卡小游戏,如下所示:
当用户在文本框中输入正确答案后,单词“Correct!”应该以粗体显示为绿色,然后应该在不久之后删除 CSS 属性。这是输入区域的 HTML:
<div>
<input type="text" id="answer" style="width: 80%; height: 30px;" placeholder="Enter your answer..." onkeyup="checkAnswer(this,event);" autofocus><br>
</div>
这是应该执行上述操作的相应 javascript:
function checkAnswer(input, event){
if(event.keyCode == 13){
var answer = document.getElementById("answer").value.toLowerCase();
var answer_style = document.getElementById("answer");
for(var i = 0; i<qs.length; i++){
if(answer == qs[cardIndex]["a"].toLowerCase()){
**input.setAttribute("style", "color:green; font-weight:bold;");**
input.value = "Correct!";
setTimeout(function(){input.value="";},1000);
**input.removeAttribute("style");**
}else{
input.value = "Incorrect!";
setTimeout(function(){input.value="";},1000)
}
}
if(input.value == "Correct!"){
nextCard();
}
}
}
除了 setAttribute 和 removeAttribute 方法外,checkAnswer 函数中的所有内容都在代码片段中加了星号。我试过将 removeAttribute 方法放在 for 循环之后,但这不起作用。如果我不包括 removeAttribute 方法,setAttribute 方法可以工作,但我不希望文本保持绿色。
如果有人能帮我解决这个问题那就太好了!
如果您需要更多信息来理解问题,请随时提问!
谢谢!
最佳答案
您在添加 style
属性后立即将其删除。删除需要安排在以后进行(即 进入 传递给 setTimeout
的函数),就像 input.value="";
一样.
if(answer == qs[cardIndex]["a"].toLowerCase()){
input.setAttribute("style", "color:green; font-weight:bold;");**
input.value = "Correct!";
} else{
input.value = "Incorrect!";
}
setTimeout(function(){
input.value = "";
input.removeAttribute("style");
}, 1000);
关于javascript - 为什么 .setAttribute() 和 .removeAttribute 方法在我的 javascript 代码中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20645334/