简体   繁体   中英

CSS transition on JavaScript changing style

Hello I have a div and close button on this div

and simple CloseMyDiv function to hide my div

function CloseMyDiv(){
  document.getElementById('myDiv').style.display = 'none';
}

How can I add animate like css transitions

You can't animate the display property, but you can change the opacity of the element. Like @Gerard said in the comments, use a CSS class. So, something like this.

 const div = document.querySelector('div') document.querySelector('button').addEventListener('click', function(){ div.classList.toggle('hidden') })
 div { transition: 0.5s } .hidden { opacity: 0 }
 <button>Show/hide</button> <div>i am a div.</div>

In case you do not want the div taking up space while its hidden, you can add, say transform:scale(0) or height:0 to .hidden as well.

As @rmn mentioned, you cannot animate the display property and you don't want your div to take the space after it closes, so you can apply the below sample code:-

HTML -

<div id="myDiv">Just a div</div>
<button id="btn" type="button">Close Div</button>

CSS -

div{
  width:200px;
  height:200px;
  background:white;
  color:black;
  border:1px solid black;
  transition:all 2s;
  overflow:hidden;
}

.closed{
  height:0px;
  width:0px;
  border:0;
}

Javascript -

function closeMyDiv(){
  document.getElementById('myDiv').classList.toggle('closed');
}

document.getElementById('btn').onclick = function(){
  closeMyDiv();
}

Here is the fiddle - http://jsfiddle.net/m07nhzsk/13/

Hope this helps. Cheers !!

If you want a sliding animation, you can try using a very short jQuery code (it's still Javascript, though).

 $('#closeBtn').click(function(){ $('.toBeClosed').slideToggle(); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <div class="toBeClosed">Div element</div> <button id="closeBtn">Close</button>

You can easily remove the click function if you want the code to run without clicking.

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