简体   繁体   English

使用 Javascript、CSS 和 HTML 的按钮颜色更改帮助

[英]Button color change help using Javascript, CSS, and HTML

I am working on how to change the color of the buttons when one is clicked and also to change the color of the button at different times.我正在研究如何在单击按钮时更改按钮的颜色,以及如何在不同时间更改按钮的颜色。 But there seems to be a problem with my code.但是我的代码似乎有问题。 I need an extra pair of eyes to see my problem.我需要一双额外的眼睛才能看到我的问题。 Here is my JS Fiddle .这是我的JS Fiddle Thanks in advance.提前致谢。

<button id="start" class="colorChange" onclick="colorChange(this)" style="background-color: black"></button>
<button id="here" class="colorChange" onclick="colorChange(this)"data-color="orange" style="background-color: black"></button>
<button id="now" class="colorChange" onclick="colorChange(this)"data-color="yellow" style="background-color: black">

function colorChange(obj) {
    var buttons = document.getElementsByTagName("button");
    for(var i=0; i<buttons.length; i++) {
    buttons[i].style.backgroundColor = "#000000";}

 obj.style.backgroundColor=getAttribute('data-color');
    if(obj == "start"){setTimeout(changeColor, 2000)}}

function changeColor(){
    var buttons = document.getElementsByTagName("button");
    for(var i=0;i<buttons.length;i++){
        var color = buttons[i].getAttribute('data-color');
        buttons[i].style.backgroundColor = color;}
}

You have a reference error here:您在这里有一个参考错误:

obj.style.backgroundColor=getAttribute('data-color');

it should be:它应该是:

obj.style.backgroundColor=obj.getAttribute('data-color');

You also need to put this code before the markup (f.ex in the <head> ): http://jsfiddle.net/jRSz6/4/您还需要将此代码放在标记之前(f.ex 在<head> ): http : //jsfiddle.net/jRSz6/4/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM