javascript - 为什么 .setAttribute() 和 .removeAttribute 方法在我的 javascript 代码中不起作用?

标签 javascript html css

我创建了一个抽认卡小游戏,如下所示:

enter image description here

当用户在文本框中输入正确答案后,单词“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/

相关文章:

jquery - 如何在 javascript 中设置滚动条处理程序?

html - <svg> 元素匹配子元素的宽度和高度

javascript - 关于 AngularJS $RouteParams

javascript - 滚动位置为 "overflow: auto"的 div

Php Auto Resize image,图像自动调整大小,但不作为调整大小的图像保存在文件夹中

html - 增加 UL 列表元素符号的宽度

Javascript 分配的 CSS 背景图像问题

javascript - 浏览器后退按钮asp.net

JavaScript/HTML/CSS : Zooming

javascript - html webview android 中的 Cookie