简体   繁体   中英

How to change a property of a CSS class dynamically using javascript (no JQuery)

I am trying to perform a transition (reducing or extending the height of a DIV). I would like to know how to go about altering a specific property (in this case 'height') associated with a specific class involved in the transition before invoking the transition by changing the CSS classname associated with the element using javascript?

So in the example below, I would like to change the 'height' property of '. sboxopen' from 130px to 360px. Then invoking the transition by changing the element's class name - > Object.className = 'sboxopen';

CSS classes:

.sbox{
height: 0px;
transition: height 1s ease-out;
overflow: hidden;
}
.sboxopen{
height: 130px;
transition: height 1s ease-out;
overflow: hidden;
}

TRANSISTION USING JAVASCRIPT:

 Object.className = 'sbox';

or

 Object.className = 'sboxopen';

If I cannot change the property of the classes, how do I go about creating a new CSS class dynamically using javascript so that I can incorporate the desired 'height' property for my desired transition?

I don't know what triggers your animation, but let's say it's a click on each of the .sbox elements.

As you can't change the CSS, you can instead use the script to add an inline style height using .style.height .

Here is a snippet:

 var sboxes = document.querySelectorAll(".sbox"); sboxes.forEach(function(box, index){ box.onclick = function(){ box.style.height = "360px"; box.className = 'sboxopen'; } }) 
 .sbox { height: 0px; transition: height 1s ease-out; overflow: hidden; border: 8px solid gray; /* Added for better visibility */ } .sboxopen { height: 130px; transition: height 1s ease-out; overflow: hidden; border: 8px solid gray; /* Added for better visibility */ } 
 <div class='sbox'>Box 1</div> <br> <div class='sbox'>Box 2</div> <br> <div class='sbox'>Box 3</div> 

⋅ ⋅ ⋅

Then, we can imagine using custom heights from a custom attribute, for each of the .sbox :

 var sboxes = document.querySelectorAll(".sbox"); sboxes.forEach(function(box, index){ box.onclick = function(){ box.style.height = box.getAttribute('myHeight'); box.className = 'sboxopen'; } }) 
 .sbox { height: 0px; transition: height 1s ease-out; overflow: hidden; border: 8px solid gray; /* Added for better visibility */ } .sboxopen { height: 130px; transition: height 1s ease-out; overflow: hidden; border: 8px solid gray; /* Added for better visibility */ } 
 <div class='sbox' myHeight='30px'>Box 1</div> <br> <div class='sbox' myHeight='60px'>Box 2</div> <br> <div class='sbox' myHeight='360px'>Box 3</div> 

Feel free to comment if any.

Hope it helps.

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