更改div的颜色

时间:2018-10-16 23:11:06

标签: javascript html

我是编码的新手,所以我正在做一些练习,其中我需要使用javascript来更改html文件中盒子的图像。尽管我使用了与所有其他脚本相同的语法,但除“蓝色”按钮外,其他所有东西似乎都在工作。谁能告诉我我所缺少的吗?

document.getElementById("button1").addEventListener("click", function() {

    document.getElementById("box").style.height = "250px"

});

document.getElementById("button2").addEventListener("click", function() {

    document.getElementById("box").style.color = "blue"

});

document.getElementById("button3").addEventListener("click", function() {

    document.getElementById("box").style.opacity = 0.5

});

document.getElementById("button4").addEventListener("click", function() {

    document.getElementById("box").style.height = "150px"

    document.getElementById("box").style.opacity = 1

    document.getElementById("box").style.color = "orange"

});
<!DOCTYPE html>
<html>
<head>
    <title>Javascript Intro</title>
    <script type="text/javascript" src="javascript.js"></script>
    
</head>
<body>

    <p>Press the buttons to change the box!</p>

    <div id="box" style="height:150px; width:150px; background-color:orange; margin:25px"></div>

    <button id="button1">Grow</button>
    <button id="button2">Blue</button>
    <button id="button3">Fade</button>
    <button id="button4">Reset</button>

    <script type="text/javascript" src="javascript.js"></script>

</body>
</html>

3 个答案:

答案 0 :(得分:4)

更改此:

document.getElementById("box").style.color = "blue";

对此:

document.getElementById("box").style.backgroundColor = "blue";

应该没问题。确保对重置按钮执行相同操作。

之所以起作用,是因为colorbackgroundColor改变了2种不同的事物。 color更改文本颜色,而backgroundColor更改元素的背景颜色。

希望有帮助。

答案 1 :(得分:0)

document.getElementById("button2").addEventListener("click", function() {
    console.log(document.getElementById("box"));
    document.getElementById("box").style.backgroundColor = "blue";
    document.getElementById("box").style.color = "red";

});

 <div id="box" style="height:150px; width:150px; background-color:orange; margin:25px">Hello</div>

将以红色显示文本。

答案 2 :(得分:0)

您应该按照其他人的解释将.color更改为.backgroundColor

此外,值得一提的是,您可以像这样使用jQuery :(我认为jQuery的方法更易于阅读和使用,特别是如果您想同时更改多个attr的话)

<script>
$(document).ready(function() {
    $("#button1").click(function(){
        $("#box").css('height', '250px');
    });

    $("#button2").click(function(){
        $("#box").css('background-color', 'blue'); 
    });

    $("#button3").click(function(){
        $("#box").css('opacity', '0.5');
    });

    $("#button4").click(function(){
        $("#box").css('opacity', '1')
                 .css('background-color', 'orange')
                 .css('height', '150px');
    });

});
</script>
相关问题