简体   繁体   中英

How to “cycle” through elements (show/hide) using JavaScript?

I have a page that includes elements like these:

<div id="1" style="display: block;">
[...]
</div>
    
<div id="2" style="display: none;">
[...]
</div>
    
<div id="3" style="display: none;">
[...]
</div>
    
<button id="next" onclick="ScrollNext()">
    
<button id="previous" onclick="ScrollPrevious()">

When a user clicks "next", I want to determine which [div] is currently showing as "display: block;" modify that [div]'s style to "display: none;", and then modify the next sequential [div]'s style to "display: block;" (and of course I want to do the opposite when the user clicks the "previous" button)

I know how to write code for a button to toggle a single element this way, but how can I determine programmatically which element's style to modify?

I have an implementation using JavaScript as below. I have given distinct color to the div for the sake of observing the change. We basically make use of nextElementSibling and previousElementSibling properties of the Node to cycle forward and backward. Finding the current visible node is just a .find away.

 const divs = [...document.querySelectorAll('.container')]; function getVisibleDiv() { const visibleDiv = divs.find(div => div.style.display === 'block'); return visibleDiv; } function next() { const visibleDiv = getVisibleDiv(); visibleDiv.style.display = 'none'; if (visibleDiv.nextElementSibling?.className === 'container') visibleDiv.nextElementSibling.style.display = 'block'; else { divs[0].style.display = 'block'; } } function previous() { const visibleDiv = getVisibleDiv(); visibleDiv.style.display = 'none'; if (visibleDiv.previousElementSibling?.className === 'container') visibleDiv.previousElementSibling.style.display = 'block'; else { divs[divs.length - 1].style.display = 'block'; } }
 .container { width: 100px; height: 100px; background: green; }.container:nth-child(2) { background: orange; }.container:nth-child(3) { background: yellow; }
 <div id="1" class='container' style="display: block;"> </div> <div id="2" class='container' style="display: none;"> </div> <div id="3" class='container' style="display: none;"> </div> <button id="next" onclick="next()">Next</button> <button id="previous" onclick="previous()">Prev</button>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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