简体   繁体   English

如何使用事件监听器使用JavaScript更改背景

[英]How to change the background with javascript using an event listener

This is my HTML and Javascript, I decided not to include my CSS as don't think its needed. 这是我的HTML和Javascript,我决定不包括CSS,因为认为不需要它。 The purpose for my code is to create a toggle switch (like an iPhone setting in the settings app) then to add an event listener using javascript. 我的代码的目的是创建一个切换开关(例如settings应用程序中的iPhone设置),然后使用javascript添加事件监听器。 I made the Listener apply to the button element. 我使监听器应用于button元素。 When I click on the button, the function, start(), should activate and as you can see, the toggle function should activate when the onclick event is initiated. 当我单击按钮时,函数start()应该激活,并且如您所见,触发onclick事件时应该激活切换功能。 Which should change the background color when the button is pressed. 按下按钮时应更改背景颜色。 However, it simply does not change color. 但是,它根本不会改变颜色。 Its like the toggle call is not working. 就像切换调用不起作用一样。 I could call the toggle function separately but this changes the color when the page loads. 我可以分别调用切换功能,但这会在页面加载时更改颜色。 It should work when I click the button. 当我单击按钮时,它应该可以工作。 Thank you for anyone that can help me. 感谢您能为我提供帮助的任何人。

<!DOCTYPE html>
<html>

<head>
  <title>Light Switch</title>
  <link rel="stylesheet" href="light.css" />
</head>

<body id="body">

  <button id="submit">Submit
    <label id="switch">
      <input type="checkbox" checked>
      <span class="slider"></span>
    </label>
  </button>
  <script src="light.js"></script>

</body>
</html>


//This js file was separate from my HTML file and was linked

function start() {
  var submit = document.getElementById("submit");
  submit.addEventListener("onclick", toggle);
};

function toggle() {
  var color = document.getElementById("body");
  color.style.backgroundColor = "black";
};

start();

Change onclick to only click .Also there seems to be no need of the start() function in this case. onclick更改为仅click 。在这种情况下,似乎也不需要start()函数。

 document.getElementById("submit").addEventListener("click", toggle); function toggle() { console.log('c') document.getElementById("body").style.backgroundColor = "black"; }; 
 <body id="body"> <button id="submit">Submit <label id="switch"> <input type="checkbox" checked> <span class="slider"></span> </label> </button> </body> 

Also to use onclick you don't need addEventListener 另外,使用onclick不需要addEventListener

 var getSubmitButton = document.getElementById("submit"); getSubmitButton.onclick = toggle; function toggle() { document.getElementById("body").style.backgroundColor = "black"; }; 
 <body id="body"> <button id="submit">Submit <label id="switch"> <input type="checkbox" checked> <span class="slider"></span> </label> </button> </body> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM