javascript - 用滑动代替跳跃然后改变模式
问题描述
我的任务是使用现有代码在 javascript 中创建动画并进行更改以做两件事。切换模式,然后继续,直到该人关闭程序。四种模式是:
模式 0 - 从左到右
模式 1 - 从上到下
模式 2 - 从右到左
模式 3 - 自下而上
从模式 0 切换到 1 是麻烦开始的地方。它应该滑动,但当我到达那里时它会跳动。
下面是我的代码。
<!DOCTYPE html>
<html>
<style>
#container {
width: 400px;
height: 400px;
position: relative;
background: yellow;
}
#animate {
width: 50px;
height: 50px;
position: absolute;
background-color: red;
}
</style>
<body>
<p><button onclick="myMove()">Click Me</button></p>
<div id ="container">
<div id ="animate"></div>
</div>
<script>
function myMove() {
var elem = document.getElementById("animate");
var pos = 350;
var id = setInterval(frame, 5);
}
function frame() {
if (pos == 0) {
pos++;
elem.style.bottom= pos + 'px';
} else {
pos--;
elem.style.left = pos + "px";
if (pos == 49.985) {
pos++;
elem.style.left = pos + "px";
}
}
解决方案
我建议您对 x 和 y 使用两个变量,并将 posBottom 替换为 top 样式的变量。
之前的问题是 whenpos
等于 0 并因此触发了 if 语句,它立即递增,导致它改为触发else
,然后递减,回到if
,等等。它跳起来是因为它style.bottom = 0px
导致它直接下降到底部。
function myMove() {
var elem = document.getElementById("animate");
var posLeft = 350;
var posTop = 0;
var id = setInterval(frame, 5);
function frame() {
if (posLeft == 0 && posTop != 350) {
stage=1;
posTop++;
elem.style.top= posTop + 'px';
} else if (posTop == 0) {
posLeft--;
elem.style.left = posLeft + "px";
} else if (posLeft != 350) {
posLeft++;
elem.style.left = posLeft + "px";
} else if (posTop != 0) {
posTop--;
elem.style.top= posTop + 'px';
}
}
}
#container {
width: 400px;
height: 400px;
position: relative;
background: yellow;
}
#animate {
width: 50px;
height: 50px;
position: absolute;
background-color: red;
}
<p><button onclick="myMove()">Click Me</button></p>
<div id ="container">
<div id ="animate"></div>
</div>
推荐阅读
- java - 将元素名称传递给另一个类方法
- delphi - 在 DBGridEh 的复选框字段上设置默认值“0”
- python-3.x - 将 txtfile 附加到组合框 tkinter
- c# - 如何使用 Windows Active Directory 从托管在单独服务器上的前端客户端对 .Net Core WebAPI 中的用户进行身份验证?
- c# - 网格不按程序更改
- c# - 如何在 ASP.NET Core 3 上同时使用 Azure AD 身份验证和身份?
- qaf - com.qmetry.qaf.automation.step.client.ScenarioFactory.getTestsFromFile() 抛出异常
- python - Bash 中有没有办法确定字符串中是否存在字符?
- r - 将 P 值添加到组箱线图中的比较
- php - SQL - 结合两个具有不同 WHERE 原因的 COUNT 和 GROUP BY 用户名