JavaScript:单击按钮时无法更改div的背景颜色

时间:2014-10-04 15:33:22

标签: javascript html css

您好我想在点击按钮时更改div的背景颜色,然后再将其更改回来,但我无法通过...请帮助一下......谢谢!

window.onload = function (){
    var oBtn1 = document.getElementById('btn1');
    var oDiv = document.getElementById('div1');
    var sDivClass = oDiv.className;

    oBtn1.onclick = function() {
        if (sDivClass == 'div1') {
            sDivClass = 'toGreen';
            oBtn1.value = 'to Red';
        } else {
            sDivClass = 'div1';
            oBtn1.value = 'To Green';
        }
    }
}

HTML:

<div class="div1" id="div1"></div>
<input id="btn1" type="button" value="To Green" />

CSS:

.div1 {
    width:100px;
    height: 100px;
    background-color: red;
}

.toGreen {
    width:100px;
    height: 100px;
    background-color: green;
}

2 个答案:

答案 0 :(得分:1)

您只是更改局部变量的值,而不是与DIV关联的类。尝试

 oBtn1.onclick = function() {
                    if (oDiv.className === 'div1') {
                        oDiv.className = 'toGreen';
                        oBtn1.value = 'to Red';

                    } else {
                        oDiv.className = 'div1';
                        oBtn1.value = 'To Green';
                    }
 };

答案 1 :(得分:0)

您的代码中存在两个问题。首先,您实际上并没有为div分配新的类名。第二个是,如果类名是div1,则新类应该变为div1 toGreen,而不仅仅是toGreen(该div仍然具有来自div1类的基本样式)。固定代码:

window.onload = function () {
    var oBtn1 = document.getElementById('btn1');
    var oDiv = document.getElementById('div1');

    oBtn1.onclick = function () {
        if (oDiv.className == 'div1') {
            oDiv.className = 'div1 toGreen';
            oBtn1.value = 'to Red';
        } else {
            oDiv.className = 'div1';
            oBtn1.value = 'To Green';
        }
    }
};