为什么.setAttribute()和.removeAttribute方法在我的javascript代码中不起作用?
我创建了一个小的抽认卡游戏,如下所示: 用户在文本框中输入正确答案后,“correct!”一词应该以绿色粗体显示,然后CSS属性应该很快被删除。以下是输入区域的HTML:为什么.setAttribute()和.removeAttribute方法在我的javascript代码中不起作用?,javascript,html,css,Javascript,Html,Css,我创建了一个小的抽认卡游戏,如下所示: 用户在文本框中输入正确答案后,“correct!”一词应该以绿色粗体显示,然后CSS属性应该很快被删除。以下是输入区域的HTML: <div> <input type="text" id="answer" style="width: 80%; height: 30px;" placeholder="Enter your answer..." onkeyup="checkAnswer(this,event);" autofocus
<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();
}
}
}
功能检查应答(输入、事件){
如果(event.keyCode==13){
var answer=document.getElementById(“answer”).value.toLowerCase();
var answer_style=document.getElementById(“answer”);
对于(var i=0;i您在添加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);
您正在设置属性并同时将其删除。如果目标是在一秒钟延迟后将其删除,则类似于:
setTimeout(function(){
input.value="";
input.removeAttribute("style");
},1000);
将input.removeAttribute放入setTimeout函数中:
setTimeout(function(){input.value="";input.removeAttribute("style");},1000);
这将在1秒后删除样式。我认为输入。删除属性(“样式”);
正在删除最初设置的整个样式。我建议的另一种更简单的方法是,分配一些CSS类并基于该类定义样式。使用setAttribute和removeAttribute方法可能没有用处,但会提供相同的功能。是否应该将removeAttribute
放入setTimeout
调用b中阿克?谢谢你帮我!