如何修复代码以使按钮褪色并在单击时将按钮更改为蓝色?

时间:2019-01-10 18:57:34

标签: javascript function events

我正在尝试创建一个JavaScript事件,单击button2会将其更改为蓝色。然后点击button3,它就会淡出方框。

我还有另外两个动作导致button1增大,button4重置它,但是我无法使其他两个起作用。我需要在代码中修复什么?

document.getElementById("button1").addEventListener("click",function(){
  document.getElementById("box").style.height = "250px";
})

document.getElementById("button2").addEventListener("click",function(){
  document.getElementById("box").style.backgroundcolor = "blue";
});

document.getElementById("button3").addEventListener("click",function(){
  document.getElementById("box").fadeOut();
});

document.getElementById("button4").addEventListener("click",function(){
   document.getElementById("box").style.height = "100px";
});

1 个答案:

答案 0 :(得分:0)

关于按钮2,样式属性区分大小写,您正在寻找backgroundColor

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

关于按钮3,没有本机javascript fadeOut()函数,我假设您正在尝试使用同名的jQuery函数。为此,您需要确保包含jQuery并使用jQuery选择器选择元素:

$('#box').fadeOut();

请参见以下代码段:

document.getElementById("button1").addEventListener("click",function(){
  document.getElementById("box").style.height = "250px";
})

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

document.getElementById("button3").addEventListener("click",function(){
  $('#box').fadeOut();
});

document.getElementById("button4").addEventListener("click",function(){
   document.getElementById("box").style.height = "100px";
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="button1">Button 1</button>
<button id="button2">Button 2</button>
<button id="button3">Button 3</button>
<button id="button4">Button 4</button>

<div id="box" style="height: 50px; width: 300px; background-color: #ff0000; margin-top: 10px;">
 &nbsp;
</div>