简体   繁体   中英

Transition a DIV element while reverting transition on a another element - Using Javascript

I have php generating several DIV tags populated with information for a database. A DIV height of 400px will display all information. However, I render the DIVs to height=50PX on the page with CSS.

example:

<div style="height: 50px">Info</div>
<div style="height: 50px">Info</div>
<div style="height: 50px">Info</div>
<div style="height: 50px">Info</div>

etc

I need some help with javascript method and functions, that will run when I click on the DIV element, the function should change the style.property.height to 400px and simultaneously reduce any other div that was expanded to 400px back to 50px. When the DIV is action ie it's at 400px, it should NOT change no matter how many time it's clicked on, but once click out of the DIV or another div it should revert to 50px

You can give all the div s the same class to select them by (with document.querySelectorAll ) to change their styles. You can loop through all of the div s with Array.prototype.forEach to change their heights back to 50px . JSFiddle: http://jsfiddle.net/s5dLpjkg/embedded/result

 var divs = document.querySelectorAll(".myClass"); var input = document.getElementById("num"); document.getElementById("transitionBtn").addEventListener("click", function(e){ var num = input.value; var div = divs[num-1]; [].slice.call(divs).forEach(function(el){ if(el.style.height!=="50px"&&el!==div){ el.style.height = "50px"; } }); div.style.height="200px"; }); 
 .myClass{ background-color: dodgerblue; border: 1px solid black; transition: height 2s; } 
 <div style="height: 50px" class="myClass">Info #1</div> <div style="height: 50px" class="myClass">Info #2</div> <div style="height: 50px" class="myClass">Info #3</div> <div style="height: 50px" class="myClass">Info #4</div> <input type="number" id="num" placeholder="Div number" min="1" max="4" style="width: 30%" value="1"> <p/> <button id="transitionBtn">Run Transition</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