简体   繁体   中英

Moving a div up and then down

I have my code that supposes to animate div in a way that it moves up and then down. But it doesn't work and I don't know why.

 document.getElementById('div').style = 'width: 50px; height: 50px; background-color: blue; left: 10px; bottom: 10px; position: absolute; animation-name: up; animation-duration: 2s;'; setTimeout(function() { document.getElementById('div').style = 'width: 50px; height: 50px; background-color: blue; left: 10px; bottom: 10px; position: absolute; animation-name: down; animation-duration: 2s;' }, 2 * 1000); setTimeout(function() { document.getElementById('div').style = 'width: 50px; height: 50px; background-color: blue; left: 10px; bottom: 10px; position: absolute;' }, 2 * 1000);
 @keyframes up { from (bottom: 10); to (bottom: 50); } @keyframes down { from (bottom: 50); to (bottom: 10); }
 <div id="div"></div>

With the translateY property you can move an html element up or down. Just use it in a css animation and you are fine:

@keyframes upToDown {
  0% {
    transform: translateY(0);
  }
  50% {
    transform: translateY(-30px);
  }
  100% {
    transform: translateY(0);
  }
}

Here you have the full example:

 div { background: red; margin-top: 50px; animation: upToDown 2s infinite; } @keyframes upToDown { 0% { transform: translateY(0); } 50% { transform: translateY(-30px); } 100% { transform: translateY(0); } }
 <div> a div </div>

css is enough!

 @keyframes upAndDown { 0% { bottom: 5px; } 100% { bottom: 10px; } } .wrapper { position: relative; width: 100px; height: 100px; border: 1px solid black; } .content { position: absolute; bottom: 5px; width: 20px; height: 20px; background-color: red; animation: upAndDown 1s ease-in-out 2s infinite; }
 <div class="wrapper"> <div class="content"></div> </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