2017-02-24 28 views
0

我需要将HTML标记中的元素从黑色更改为红色,并将颜色再次变为黑色。我有一个简单的按钮,它通过添加类的元素加1当我按下按钮时,如何更改HTML标记中的颜色?

<html> 
<head> 
<body> 
    <div id="e">0</div> 
    <input type="button" onclick="foo()" value="Ok"> 

    <script> 
     var e = 0 
     function foo(){ 
      kak = document.getElementById('e').innerHTML = e += 1 
     } 
    </script> 

</body> 
</html> 
+6

'的document.getElementById( “E”)style.color = “红色”;' – artemisian

回答

2

我会接近这一点,然后通过CSS扎那类颜色样式。这是我正在谈论的一个例子。

<html> 
    <head> 
    <style> 
     #input-button { background-color: black; color: white; } 
     #input-button.red { background-color: red } 
    </style> 
    </head> 
    <body> 
    <div id="e">0</div> 
    <input id="input-button" type="button" onclick="foo()" value="Ok"> 

    <script> 
     var e = 0 
     function foo(){ 
     var el = document.getElementById('e'); 
     el.innerHTML = e += 1; 

     var button = document.getElementById('input-button'); 
     button.classList.add('red'); 

     // setTimeout begins a timer, and I pass 500ms. To 
     // make this longer, increase the number below 
     setTimeout(function(){ 
      button.classList.remove('red'); 
     }, 500) 

     } 
    </script> 
    </body> 
</html> 

下面是一个例子 jsfiddle

相关问题