Dom 背景颜色操作

Dom background color manipulation

提问人:user22922919 提问时间:11/16/2023 最后编辑:Daviduser22922919 更新时间:11/16/2023 访问量:30

问:

我正在尝试更改 html 文件中其他段落的背景颜色。我正在为此使用循环来减少冗余。无论我做什么,它都对我不起作用。关于如何更轻松地做到这一点的任何建议?

JS逻辑:

document.addEventListener('DOMContentLoaded', function () {
  // Add event listener to the button
  document.getElementById('changeBackgroundBtn').addEventListener('click', changeBackground);
  
  function changeBackground() {
    console.log('changeBackground() called');
    // Get the div containing paragraphs
    const parasDiv = document.getElementById('paras');

    // Get all paragraphs inside the div
    const paragraphs = parasDiv.getElementsByTagName('p');

    // Loop through paragraphs and change background color for every other paragraph
    for (let i = 0; i < paragraphs.length; i++) {
      // Check if the index is odd (every other paragraph)
      if (i % 2 === 0) {
        // Toggle background color between lightblue and white
        paragraphs[i].style.backgroundColor =
          paragraphs[i].style.backgroundColor === 'lightblue' ? '' : 'lightblue';
      }
    }
}});
<div class="container">
  <h1>Basic DOM Manipulation</h1>
  <p>
    <button id="changeBackgroundBtn" class="btn btn-primary" type="button">
  Change Background
</button> 

JavaScript HTML DOM 部署

评论

1赞 David 11/16/2023
显示的代码正在产生错误,因为没有值为 的元素。您在测试时是否在浏览器控制台中观察到相同的错误?id"paras"
1赞 Professor Abronsius 11/16/2023
大概只是简单地使用CSS,并且由于某种原因不是一种选择?nth-of-type

答:

1赞 Professor Abronsius 11/16/2023 #1

根据上面的评论,您可以使用 css 中的属性来定位每个第 2 个元素。下面的按钮只是切换父容器上的类,剩下的工作由 css 规则完成。nth-of-typep

document.querySelector('button').addEventListener('click',e=>{
  e.target.previousElementSibling.classList.toggle('colours');
})
p{
  background:white;
  padding:1rem;
  font-family:monospace;
}

.container.colours p:nth-of-type(even){
  background:lightblue;
  color:darkblue;
}
<div class='container'>
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed dapibus leo in diam bibendum, a bibendum tellus congue. Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>

  <p>Praesent pellentesque fringilla pharetra. Suspendisse eget felis eget erat viverra placerat. Aliquam id tincidunt ligula, in cursus nunc.</p>

  <p>nteger pretium magna nec arcu pellentesque ullamcorper. Pellentesque rhoncus nunc sed urna tempor, sed pretium nunc sollicitudin.</p>

  <p>Duis placerat erat eu odio finibus dignissim. Duis rhoncus, velit non aliquam elementum, risus arcu sollicitudin sapien, eu egestas purus ex vel risus.</p>

  <p>Etiam lobortis ligula sit amet purus ornare facilisis. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae;</p>

  <p>Donec bibendum pharetra sapien id tincidunt. Proin metus ante, pellentesque vel dui sed, lobortis ultricies justo. Proin accumsan ultrices ex, at aliquam erat lobortis vel.</p>

  <p>Vivamus rutrum leo urna, eget porta neque condimentum sed. Nunc fermentum ullamcorper mattis. Sed a malesuada velit. Aenean porttitor sagittis neque, consectetur pharetra enim tristique eget.</p>

  <p>Nam et convallis felis. Maecenas sit amet viverra ex. Suspendisse potenti. Donec dictum faucibus gravida. Duis molestie lorem sed turpis tincidunt rhoncus. Vivamus nunc nulla, sagittis sed lectus non, fermentum placerat massa. Praesent ac tristique sapien.</p>

  <p>Aenean tristique aliquet lacinia. Curabitur vitae bibendum libero, vitae rhoncus nunc. Proin lobortis, ipsum a venenatis blandit, justo augue placerat odio, quis pretium tortor ipsum nec felis.</p>
</div>


<button>Change</button>