问题
Encountering the following issue when trying to combine CSS
transitions with JS
event handlers. I know how to use CSS transition property for example:
div {
width: 50px;
height: 50px;
background: blue;
transition: width 2s;
}
div:hover {
width: 300px;
}
<div></div>
I also know how to put a click handler on an DOM
element like this:
let eventDiv = document.querySelector('#clickMe');
let hiddenDiv = document.querySelector('#hiddenDiv');
eventDiv.onclick = () => {
if(hiddenDiv.style.display === 'block') {
hiddenDiv.style.display = 'none'
} else{
hiddenDiv.style.display = 'block';
}
}
#clickMe{
width: 100px;
height: 50px;
background-color: blue;
}
#hiddenDiv {
width: 100px;
height: 50px;
background-color: green;
display: none;
}
<div id="clickMe"></div>
<div id="hiddenDiv"></div>
Question
How do I combine the two and get a CSS
transition (<div>
should not appear immediately but should slide in) when I toggle the visibility of the <div>
with a JS
onclick event?
回答1:
As per my comment, to combine the js and transition, you need to add and remove a class that changes the property that you want to transition.
In the below snippet, I add and remove a class of hide, which changes the height (that has a trnasition on it)
let eventDiv = document.getElementById('clickMe');
let hiddenDiv = document.getElementById('hiddenDiv');
eventDiv.onclick = () => {
if(hiddenDiv.classList.contains("hide")) {
hiddenDiv.classList.remove("hide");
} else{
hiddenDiv.classList.add("hide");
}
}
#clickMe{
width: 100px;
height: 50px;
background-color: blue;
}
#hiddenDiv {
width: 100px;
height: 50px;
background-color: green;
overflow:hidden;
transition: height 1s;
}
#hiddenDiv.hide {
height: 0;
}
<div id="clickMe"></div>
<div id="hiddenDiv" class="hide"></div>
回答2:
The problem here is that you cannot give transition
to display
property:
div {
width: 50px;
height: 50px;
background: blue;
transition: 2s;
}
div:hover {
display:none;
}
<div></div>
What you can do is to use opacity
instead.
let eventDiv = document.querySelector('#clickMe');
let hiddenDiv = document.querySelector('#hiddenDiv');
eventDiv.onclick = () => {
if(hiddenDiv.style.opacity === '1') {
hiddenDiv.style.opacity = '0'
} else{
hiddenDiv.style.opacity = '1';
}
}
#clickMe{
width: 100px;
height: 50px;
background-color: blue;
}
#hiddenDiv {
width: 100px;
height: 50px;
background-color: green;
opacity: 0;
transition: 2s;
}
<div id="clickMe"></div>
<div id="hiddenDiv"></div>
IMPORTANT
If you choose to use this property remember to change display
to none
after the transition is over if you don't want it to be block
.
来源:https://stackoverflow.com/questions/49301316/css-transition-in-combination-with-js-clickevent