Reputation: 406
In order to manipulate height property, so I use javascript not jquery then I got a problem.
The problem is that I cannot override the height back to zero once I have set to the scrollHeight of the element.
Here is my js code:
let isClosed = true;
var cals = document.getElementsByClassName('h-strench-box');
for (var i = 0; i < cals.length; i ++) {
cals[i].addEventListener('click', function(e) {
if (isClosed) {
this.classList.add('h-strench-box-out');
var content = this.querySelector('.h-strench-content');
content.style.height = content.scrollHeight + 'px';
isClosed = false;
} else {
if (this.classList.contains('h-strench-box-out')) {
this.classList.remove('h-strench-box-out');
// this.querySelector('.h-strench-content').style.height = '0';
// This not working
isClosed = true;
} else {
for (var j = 0; j < cals.length; j ++) {
cals[j].classList.remove('h-strench-box-out');
cals[j].querySelector('.h-strench-content').style.height = '0';
// This not working
}
this.classList.add('h-strench-box-out');
var content = this.querySelector('.h-strench-content');
content.style.height = content.scrollHeight + 'px';
}
}
});
}
css
.h-strench-content {
height: 0;
padding: 0;
display: none;
overflow: hidden;
transition: height 0.4s ease-in;
}
.h-strench-box-out .h-strench-content {
display: block;
}
.h-strench-btn {
transition: transform 0.3s ease-out;
}
.h-strench-btn::before {
content: '\f13a';
font-family: "Font Awesome 5 Free";
font-size: 27px;
font-weight: 600;
}
One more question. How can I change the height value(B) not element.style
(A). Please compare the picture below. Please help thank you!
Upvotes: 0
Views: 87
Reputation: 743
First step: make sure your querySelector calls are returning the correct elements. It will always return the first element that matches the selector.
As for the css: Height A is inline css, meaning it will always have priority over height B unless height B is marked !important
. In order to revert to height B, height A must be removed entirely via remove property or simply set to null.
var obj = document.getElementById('name');
obj.style.removeProperty('height');
// if you want to return the old value...
// var oldValue = obj.style.removeProperty('height');
If you want to change contents in a stylesheet, see this example:
var declaration = document.styleSheets[0].rules[0].style;
var oldValue = declaration.removeProperty('height');
... However, be careful with the stylesheet example, as a change of indices can throw this off. It would be much safer to find an alternative that adds/removes classes with the values you desire instead.
Upvotes: 1