Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/455.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/73.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript可以';不要让按钮改变盒子的颜色_Javascript_Html_Colors - Fatal编程技术网

Javascript可以';不要让按钮改变盒子的颜色

Javascript可以';不要让按钮改变盒子的颜色,javascript,html,colors,Javascript,Html,Colors,单击框时没有更改框的颜色,代码中的错误在哪里?您需要删除.body,因为您已经选择了前面有框id的元素 document.getElementById("button2").addEventListener("click", function({ document.getElementById("box").body.style.backgroundColor = "Blue"; }); 使用querySelector选择元素。并像这样处理按钮的单击事件 var btn=document

单击框时没有更改框的颜色,代码中的错误在哪里?

您需要删除
.body
,因为您已经选择了前面有框id的元素

document.getElementById("button2").addEventListener("click", function({
  document.getElementById("box").body.style.backgroundColor = "Blue";
});

使用
querySelector
选择元素。并像这样处理按钮的单击事件

var btn=document.querySelector(“按钮2”)//选择你的按钮
btn.addEventListener('click',function(){//处理click事件
document.querySelector(“#box”).style.backgroundColor=“Blue”//选择框id并设置背景
});
点击

变色


你做错了。有两种方法可以做到这一点

第一::

document.getElementById(“button2”).addEventListener(
“点击”,
函数(){
document.getElementById(“box”).style.backgroundColor=“蓝色”;
}

);您的javascript应该如下所示:


document.getElementById(“button2”).addEventListener(“单击”,函数(){document.getElementById(“box”).style.backgroundColor=“蓝色”;})

和您的(“”)HTML?控制台中有任何错误吗?用
document.getElementById(“box”)替换
document.getElementById(“box”).style.backgroundColor
我对此非常陌生,我有一个正在运行的grow函数,它是//grow Button document.getElementById(“button1”).addEventListener(“单击”,函数(){document.getElementById(“box”).style.height=“250px”;};//蓝色按钮document.getElementById(“button2”).addEventListener(“单击”,函数(){document.getElementById(“box”).body.style.backgroundColor=“蓝色”});请解释为什么这样做,而不仅仅是发布代码。
document.getElementById("button2").addEventListener(
    "click", 
    function(){
        document.getElementById("box").style.backgroundColor = "Blue";
    }
);