我正在尝试更改 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>
根据上面的评论,您可以使用 css 中的
nth-of-type
属性来定位每个第二个 p
元素。下面的按钮只是在父容器上切换一个类,其余的由 css 规则完成。
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>