按钮逐一着色

时间:2014-06-13 08:00:04

标签: javascript html button colors

我使用javascript为按钮上色,但是我想要按下一个按钮时所有其他按钮都是灰色的(设置为默认颜色)

这就是我的立场:

使用Javascript:

function changeBtn(btn) {
    if (! btn.style)
    {
        alert("Err!");
        return;
    }
    btn.style.background = "#acd484";
    return;
}

HTML:

<input class="submit" style="width: 200px; height: 50px; font-size:12px;" id "submit" type="button" value="Zivljensko" onclick="changeBtn(this)" />
<input class="submit" style="width: 200px; height: 50px; font-size:12px;" id "submit" type="button" value="Premozenjsko" onclick="changeBtn(this)" />
<input class="submit" style="width: 200px; height: 50px; font-size:12px;" id "submit" type="button" value="Best doctors" onclick="changeBtn(this)" />
<input class="submit" style="width: 200px; height: 50px; font-size:12px;" id "submit" type="button" value="Splosne info" onclick="changeBtn(this)" />
<input class="submit" style="width: 200px; height: 50px; font-size:12px;" id "submit" type="button" value="Splosne info" onClick="changeBtn(this)" />

如果需要,这是提交类:

.submit {
    border-top:     1px solid #ffffff;
    border-left:        1px solid #ffffff;
    border-right:       1px solid #000000;
    border-bottom:      1px solid #000000;
    padding:        0px 20px !important;
    font-size:      11px !important;
    background-color:   #fff;
    font-weight:        bold;
    color:          #453;
}

如果你理解我想要完成的事情,任何人都有任何想法:)

3 个答案:

答案 0 :(得分:0)

document.getElementsByClassName("submit").onclick = function() { 

var allButtons = document.getElementsByClassName("submit");
var count = allButtons.length;

for(var i=0;i<count;i++)
{
  if(this != allButtons[i])
    allButtons[i].style.background = "grey";
}

};

答案 1 :(得分:0)

要将所有按钮设置为灰色,除了单击的按钮之外,最简单的方法是根据submit类抓取所有按钮,然后迭代它们并设置颜色。在设置绿色之前执行此操作。

<强> Demo

function changeBtn(btn){
    if (!btn.style)
    {
        alert("Err!");
        return;
    }
    var buttons = document.querySelectorAll('.submit');
    for(var i=0; i<buttons.length; i++){
        buttons[i].style.background = 'grey';   
    }

    btn.style.background = "#acd484";
    return;
}

答案 2 :(得分:0)

我使用jQuery解决了这个问题

用这个改变你的功能

function changeBtn(btn) {
  $(".submit").removeClass("selected");
  $(btn).addClass("selected")
}

和你的css

.submit {
    border-top:     1px solid #ffffff;
    border-left:        1px solid #ffffff;
    border-right:       1px solid #000000;
    border-bottom:      1px solid #000000;
    padding:        0px 20px !important;
    font-size:      11px !important;
    background-color:   #fff;
    font-weight:        bold;
    color:          #453;
}

.selected {
  background-color:#acd484;
} 

DEMO

相关问题