使用查询选择器(JS)通过单击更改背景颜色

我已经为这些按钮编写了这段代码,因此当我单击它们时,背景颜色会发生变化,但它不起作用。问题是什么?


<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <meta http-equiv="X-UA-Compatible" content="ie=edge">

    <link rel="stylesheet" href="styles.css">

    <title>JavaScript Background Color Switcher</title>

</head>

<body>

    <div class="canvas">

        <h1>Color Scheme Switcher</h1>

        <span  class="button" id="grey"></span>

        <span  class="button" id="white"></span>

        <span  class="button" id="blue"></span>

        <span  class="button" id="yellow"></span>

    </div>

    <script src="app.js"></script>   

</body>

</html> 


JS File:

document.querySelector('.button').addEventListener('click', function btn (id) {

  document.body.style.background = id

})


湖上湖
浏览 170回答 3
3回答

慕姐4208626

您的代码有两个问题:1)document.querySelector只会返回第一个匹配的元素2) 该click事件不接受带有此类参数的函数。更好的代码是:document.querySelectorAll('.button') &nbsp;&nbsp;.forEach(btn&nbsp;=>&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;btn.addEventListener('click',&nbsp;()&nbsp;=>&nbsp;document.body.style.background&nbsp;=&nbsp;btn.id) &nbsp;&nbsp;);(这里我btn再次重用而不是使用事件中的数据,因为我已经知道你点击了哪个按钮,所以不需要乱搞ev.target...

慕虎7371278

您必须使用.querySelectorAll在所有元素上添加侦听器.button。我还纠正了你的语法addEventListenerlet btns = document.querySelectorAll('.button')btns.forEach(btn => {&nbsp; btn.addEventListener('click', evt => {&nbsp; &nbsp; document.body.style.background = evt.target.id&nbsp; })}).button { cursor: pointer; }<div class="canvas">&nbsp; <h1>Color Scheme Switcher</h1>&nbsp; <span class="button" id="grey">Grey</span>&nbsp; <span class="button" id="white">White</span>&nbsp; <span class="button" id="blue">Blue</span>&nbsp; <span class="button" id="yellow">Yellow</span></div>

德玛西亚99

使用 document.querySelectorAll 代替 document.querySelectorlet buttons = document.querySelectorAll('.button')buttons.forEach(element=>{element.addEventListener('click', (e) => {&nbsp; document.body.style.background = e.target.id&nbsp; })})span{padding: 4px 6px;border: 1px solid;cursor: pointer;}#grey{background :grey;}#white{background :white;}#blue{background :blue;}#yellow{background :yellow;}&nbsp; &nbsp; <div class="canvas">&nbsp; &nbsp; &nbsp; &nbsp; <h1>Color Scheme Switcher</h1>&nbsp; &nbsp; &nbsp; &nbsp; <span&nbsp; class="button" id="grey">gray</span>&nbsp; &nbsp; &nbsp; &nbsp; <span&nbsp; class="button" id="white">white</span>&nbsp; &nbsp; &nbsp; &nbsp; <span&nbsp; class="button" id="blue">blue</span>&nbsp; &nbsp; &nbsp; &nbsp; <span&nbsp; class="button" id="yellow">yellow</span>&nbsp; &nbsp; </div>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go