简体   繁体   中英

i want to add an animation to the div with @keyframes. I have tried basically everything i know

var style = document.createElement('style');
style.type = 'text/css';
style.innerHTML = '.moveUp{background-color:red; width:40px;height:40px;margin:auto;margin-top:3em;}'
var moveUp = document.querySelectorAll('.moveUp')
document.getElementsByTagName('head')[0].appendChild(style)


//Html

 <body>
    <div class="moveUp"></div>
    <script src="script.js"></script>
  </body>

i want the div to move down 200px them come up again

You can change the style.innerHTML to the following:

style.innerHTML = '.moveUp{background-color:red; width:40px;height:40px;margin:auto;margin-top:3em;animation: moveDown 1s;}@keyframes moveDown{50% {transform: translateY(200px);}100%{transform: translateY(0);}}'

For easier readability:

.moveUp {
  background-color: red; 
  width: 40px;
  height: 40px;
  margin: auto;
  margin-top: 3em;
  animation: moveDown 1s;
}

@keyframes moveDown {
  50% {
    transform: translateY(200px);
  }
  100%{
    transform: translateY(0);
  }
}

 var style = document.createElement('style'); style.type = 'text/css'; style.innerHTML = '.moveUp{background-color:red; width:40px;height:40px;margin:auto;margin-top:3em;animation: moveDown 1s;}@keyframes moveDown{50% {transform: translateY(200px);}100%{transform: translateY(0);}}' var moveUp = document.querySelectorAll('.moveUp') document.getElementsByTagName('head')[0].appendChild(style)
 <div class="moveUp"></div>

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