简体   繁体   中英

Animating a div element

Looking to make a specific animation for a div element. I want it to go down (smoothly) and when it reaches the bottom of the screen to come back up (smoothly).

The code I have is as follows:

The Javascript part at the If statement is where I am having difficulties. I want the box to come down and come back up smoothly.

HTML:

<div class="verticalDiv" id="verticalDiv" onclick="verticalMove()"></div>

CSS:

.verticalDiv {
  position: absolute;
  top: 0px;
  right: 500px;
  width: 100px;
  height: 100px;
  margin: 100px auto;
  background: red;
}

JS:

myVar1 = setInterval(verticalMove, 50);
v = 0;
function verticalMove() {
    redBox = document.getElementById('verticalDiv')

    redBox.style.top = v + "px";
        if (v >= 0) {
            v++;} 

        if (v === 200) {
            v--;
        }
    console.log(v);
}

I think, best way is to use css animation. You don't have to care about animation logic. Just use keyframes. Here is example:

HTML

<div id="verticalDiv" class="verticalDiv"></div>

CSS

.verticalDiv {
    height: 20px;
    width: 20px;
    background: red;
}

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

.verticalDiv.move {
    animation: move 3s ease-in-out;
}

JS

const verticalDiv = document.getElementById('verticalDiv');
verticalDiv.addEventListener('click', () => {
    verticalDiv.classList.toggle('move');
});

WORKING DEMO click on red div to start animation.

BTW If you want animate something. It is always better to animate properties that doesn't force layout updates: transform and opacity. Other properties, like top, bottom, margin are expensive for browser to animate. You should avoid them if possible. Read more

You need to differentiate between the two phases, moving down and moving up. It can be a simple true / false boolean, but storing a "speed" or "delta" value (like +/-1) is also a very typical approach.

 var v = 0; var delta=1; function verticalMove() { redBox = document.getElementById('verticalDiv') v += delta; redBox.style.top = v + "px"; if (v <= 0) delta = 1; if (v >= 50) delta = -1; } function startMove(event) { setInterval(verticalMove,30); event.target.onclick=""; } 
 .verticalDiv { position: absolute; top: 0px; right: 500px; width: 100px; height: 100px; background: red; } 
 <div class="verticalDiv" id="verticalDiv" onclick="startMove(event)"></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