web-dev-qa-db-fra.com

JavaScript - ajouter une transition entre display: none et display: block

J'utilise JavaScript pour basculer la notification comme ci-dessous. Comment puis-je ajouter une transition entre display: block et display: none;

Je ne veux pas ajouter une bibliothèque externe comme jQuery car je vais seulement utiliser l'effet toggle seul.

var btn = document.querySelector('button');

btn.addEventListener('click', function(){
  var hint = document.getElementById('hint');
  if(hint.style.display == 'none'){
    hint.style.display = 'block';
  }
  else{
    hint.style.display = 'none';
  }

});
div#hint{
  background: gold;
  color: orangered;
  padding: .5em;
  font-weight: bold;
}
<div id='hint'>
  
  <p>This is some hint on how to be safe in this community </p>
   <p>This is another hint on how to be safe in this community </p>
  </div>

<button> show hint </button>

Je sais que je peux utiliser jQuery pour y parvenir comme ci-dessous.

$(document).ready(function(){

$('button').click(function(){
$('#hint').toggle('slow');

});

});
div#hint{
      background: gold;
      color: orangered;
      padding: .5em;
      font-weight: bold;
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='hint'>
      
      <p>This is some hint on how to be safe in this community </p>
       <p>This is another hint on how to be safe in this community </p>
      </div>

    <button> show hint </button>

Puis-je faire monter et descendre le bouton progressivement pendant que le #hint est basculé comme dans l'exemple jQuery ci-dessus? Je ne veux pas que le bouton saute d'une position à une autre.

15
Abk

voir mon exemple ci-dessous:

var btn = document.querySelector('button');
var hint = document.getElementById('hint');
var height = hint.clientHeight;
var width = hint.clientWidth;
console.log(width + 'x' + height);
// initialize them (within hint.style)
hint.style.height = height + 'px';
hint.style.width = width + 'px';

btn.addEventListener('click', function(){
  if(hint.style.visibility == 'hidden'){
    hint.style.visibility = 'visible';
    //hint.style.opacity = '1';
    hint.style.height = height + 'px';
    hint.style.width = width + 'px';
    hint.style.padding = '.5em';
  }
  else{
    hint.style.visibility = 'hidden';
    //hint.style.opacity = '0';
    hint.style.height = '0';
    hint.style.width = '0';
    hint.style.padding = '0';
  }

});
div#hint{
  background: gold;
  color: orangered;
  padding: .5em;
  box-sizing: border-box;
  overflow: hidden;

  font-weight: bold;
  transition: height 1s, width 1s, padding 1s, visibility 1s, opacity 0.5s ease-out;
}
<div id='hint'>
  
  <p>This is some hint on how to be safe in this community </p>
  <p>This is another hint on how to be safe in this community </p>
</div>

<button> show hint </button>
7
arhak

Suggestion de @ vothaison: transitions CSS

Techniquement, @vothaison voulait utiliser setInterval par opposition à setTimeout, mais je n'en vois pas la nécessité. C'est juste plus de travail.

var hint = document.getElementById('hint');
var btn = document.getElementById('btn_show');

btn.addEventListener('click', function(){
  var ctr = 1;
  hint.className = hint.className !== 'show' ? 'show' : 'hide';
  if (hint.className === 'show') {
    hint.style.display = 'block';
    window.setTimeout(function(){
      hint.style.opacity = 1;
      hint.style.transform = 'scale(1)';
    },0);
  }
  if (hint.className === 'hide') {
    hint.style.opacity = 0;
    hint.style.transform = 'scale(0)';
    window.setTimeout(function(){
      hint.style.display = 'none';
    },700); // timed to match animation-duration
  }
 
});
#hint {
  background: yellow;
  color: red;
  padding: 16px;
  margin-bottom: 10px;
  opacity: 0;
  transform: scale(0);
  transition: .6s ease opacity,.6s ease transform;
}
<div id="hint" style="display: none;">
  <p>This is some hint on how to be safe in this community </p>
  <p>This is another hint on how to be safe in this community </p>
</div>

<button id="btn_show"> Show hint </button>

Utilisation d'animations CSS

var hint = document.getElementById('hint');
var btn = document.getElementById('btn_show');

btn.addEventListener('click', function(){
  hint.className = hint.className !== 'show' ? 'show' : 'hide';
  if (hint.className === 'show') {
    setTimeout(function(){
      hint.style.display = 'block';
    },0); // timed to occur immediately
  }
  if (hint.className === 'hide') {
    setTimeout(function(){
      hint.style.display = 'none';
    },700); // timed to match animation-duration
  }
});
@-webkit-keyframes in {
  0% { -webkit-transform: scale(0) rotate(12deg); opacity: 0; visibility: hidden;  }
  100% { -webkit-transform: scale(1) rotate(0); opacity: 1; visibility: visible; }
}

@keyframes in {
  0% { transform: scale(0) rotate(12deg); opacity: 0; visibility: hidden;  }
  100% { transform: scale(1) rotate(0); opacity: 1; visibility: visible; }
}

@-webkit-keyframes out {
  0% { -webkit-transform: scale(1) rotate(0); opacity: 1; visibility: visible; }
  100% { -webkit-transform: scale(0) rotate(-12deg); opacity: 0; visibility: hidden; }
}

@keyframes out {
  0% { transform: scale(1) rotate(0); opacity: 1; visibility: visible; }
  100% { transform: scale(0) rotate(-12deg); opacity: 0; visibility: hidden;  }
}

#hint {
  background: yellow;
  color: red;
  padding: 16px;
  margin-bottom: 10px;
}

#hint.show {
  -webkit-animation: in 700ms ease both;
  animation: in 700ms ease both;
}

#hint.hide {
  -webkit-animation: out 700ms ease both;
  animation: out 700ms ease both;
}
<div id="hint" style="display: none;">
  <p>This is some hint on how to be safe in this community </p>
  <p>This is another hint on how to be safe in this community </p>
</div>

<button id="btn_show"> Show hint </button>

Utiliser Vanilla JavaScript

Il y a beaucoup, beaucoup de façons de faire ce genre de chose avec Vanilla JavaScript, alors voici un bref aperçu d'une façon:

// you may need to polyfill requestAnimationFrame

var hint = document.getElementById('hint');
var btn = document.getElementById('btn_show');

btn.addEventListener('click', function(){
  var ctr = 0;
  hint.className = hint.className !== 'show' ? 'show' : 'hide';
  
  if (hint.className === 'show') {
    window.setTimeout(function(){
      hint.style.display = 'block';
      fadein();
    },0); // do this asap        
  }
  
  if (hint.className === 'hide') {
    fadeout();
    window.setTimeout(function(){
      hint.style.display = 'none';
    },700); // time this to fit the animation
  }
  
  function fadein(){
    hint.style.opacity = ctr !== 10 ? '0.'+ctr : 1;
    hint.style.transform = ctr !== 10 ? 'scale('+('0.'+ctr)+')' : 'scale(1)';
    ctr++;
    
    if (ctr < 11)
      requestAnimationFrame(fadein);
    
    else
      ctr = 0;
  }

  function fadeout(){
    hint.style.opacity = 1 - ('0.'+ctr);
    hint.style.transform = 'scale('+(1 - ('0.'+ctr))+')';
    ctr++;
    
    if (ctr < 10)
      requestAnimationFrame(fadeout);
    else
      ctr = 0;
  }
});
#hint {
  background: yellow;
  color: red;
  padding: 16px;
  margin-bottom: 10px;
  opacity: 0;
}
<div id="hint" style="display: none;">
  <p>This is some hint on how to be safe in this community </p>
  <p>This is another hint on how to be safe in this community </p>
</div>

<button id="btn_show"> Show hint </button>

Dites ce que vous voulez à propos de GreenSock, Velocity.js, jQuery, etc. - ils banalisent tous ce processus d'affichage et de masquage des choses. Pourquoi ne pas simplement emprunter les fonctions show et hide du code source de jQuery?

12
amdouglas

Sans utiliser transition css, vous pouvez utiliser js setInterval pour modifier certaines propriétés css de div, telles que:

  • Changer l'opacité de 0 à 1

  • Changer la hauteur de 0 à pleine hauteur

  • Changer la largeur de 0 à pleine largeur

Au départ, vous devriez avoir display: none; opacity: 0; height: 0; width: 0'

Ensuite, vous devez modifier display: none à display: block; avant d'utiliser setInterval pour modifier d'autres propriétés.

(Je suppose que tu sais comment cacher le div)

Vous pouvez également utiliser setTimeout (), avec une astuce récursive.

3
vothaison
var btn = document.querySelector('button');

btn.addEventListener('click', function(){
  var hint = document.getElementById('hint');
  if(hint.style.visibility == 'hidden'){
    hint.style.visibility = 'visible';
     hint.style.opacity = '1';
  }
  else{
    hint.style.visibility = 'hidden';
     hint.style.opacity = '0';
  }

});
div#hint{
  background: gold;
  color: orangered;
  padding: .5em;

  font-weight: bold;
  transition: visibility 1s, opacity 0.5s linear;
}
<div id='hint'>
  
  <p>This is some hint on how to be safe in this community </p>
   <p>This is another hint on how to be safe in this community </p>
  </div>

<button> show hint </button>

Je pense que l'utilisation de la visibilité sur l'écran est une meilleure option

2

Salut, je n'utilise pas display: block to display: none mais en changeant l'opacité, la hauteur et le rembourrage à la place, veuillez revoir celui-ci:

var btn = document.querySelector('button');

btn.addEventListener('click', function() {
  var hint = document.getElementById('hint');
  if (hint.classList.contains('h-hide')) {
    hint.classList.remove('h-hide');
  } else {
    hint.classList.add('h-hide');
  }
});
div#hint {
  display: block;
  background: gold;
  color: orangered;
  padding: .5em;
  font-weight: bold;
  transition: .5s all linear;
  opacity: 1;
  overflow: hidden;
  height: 100px;
}
#hint.h-hide {
  padding: 0;
  opacity: .25;
  height: 0;
}
<div id='hint'>

  <p>This is some hint on how to be safe in this community</p>
  <p>This is another hint on how to be safe in this community</p>
</div>

<button>show hint</button>

l'inconvénient de cette approche est que nous devons conserver la hauteur de l'indicateur div # et la modifier en utilisant javascript si nécessaire.

1
RizkiDPrast

Essayez quelque chose comme ceci:

var btn = document.querySelector('button');

btn.addEventListener('click', function(){
  var hint = document.getElementById('hint');

  hint.classList.toggle("hide");
});
.hint{
  background: gold;
  color: orangered;
  padding: .5em;
  font-weight: bold;
  
  visibility: visible;
  opacity: 1;
  max-height: 500px;
  transition: visibility 0s, opacity 0.3s, max-height 0.6s linear;
}

.hide {
  visibility: hidden;
  opacity: 0;
  max-height: 0px;
  transition: max-height 0.3s, opacity 0.3s, visibility 0.3s linear;
}
<div id='hint' class="hint">
  
  <p>This is some hint on how to be safe in this community </p>
   <p>This is another hint on how to be safe in this community </p>
  </div>

<button> show hint </button>
1
skav3n