为 div 元素设置动画

希望为 div 元素制作特定的动画。我希望它下降(平稳),当它到达屏幕底部时(平稳)回来。


我的代码如下:


If 语句中的 Javascript 部分是我遇到困难的地方。我希望盒子能顺利下来,然后再回来。


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);

}


慕少森
浏览 258回答 2
2回答

繁星淼淼

我认为,最好的方法是使用 css 动画。您不必关心动画逻辑。只需使用关键帧。这是示例:HTML<div id="verticalDiv" class="verticalDiv"></div>CSS.verticalDiv {&nbsp; &nbsp; height: 20px;&nbsp; &nbsp; width: 20px;&nbsp; &nbsp; background: red;}@keyframes move {&nbsp; &nbsp; 0% { transform: translateY(0); }&nbsp; &nbsp; 50% { transform: translateY(200px); }&nbsp; &nbsp; 100% { transform: translateY(0); }}.verticalDiv.move {&nbsp; &nbsp; animation: move 3s ease-in-out;}JSconst verticalDiv = document.getElementById('verticalDiv');verticalDiv.addEventListener('click', () => {&nbsp; &nbsp; verticalDiv.classList.toggle('move');});WORKING DEMO点击红色 div 开始动画。顺便说一句,如果你想动画的东西。为不强制布局更新的属性设置动画总是更好:变换和不透明度。其他属性,如顶部、底部、边距对于浏览器动画来说是昂贵的。如果可能,您应该避免使用它们。&nbsp;阅读更多

九州编程

您需要区分两个阶段,向下移动和向上移动。它可以是一个简单的true/false布尔值,但存储“速度”或“增量”值(如 +/-1)也是一种非常典型的方法。var v = 0;var delta=1;function verticalMove() {&nbsp; &nbsp; redBox = document.getElementById('verticalDiv')&nbsp; &nbsp; v += delta;&nbsp; &nbsp; redBox.style.top = v + "px";&nbsp; &nbsp; if (v <= 0) delta = 1;&nbsp; &nbsp; if (v >= 50) delta = -1;}function startMove(event) {&nbsp; &nbsp; setInterval(verticalMove,30);&nbsp; &nbsp; event.target.onclick="";}.verticalDiv {&nbsp; position: absolute;&nbsp; top: 0px;&nbsp; right: 500px;&nbsp; width: 100px;&nbsp; height: 100px;&nbsp; background: red;}<div class="verticalDiv" id="verticalDiv" onclick="startMove(event)"></div>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript