javascript - 如何以速度和颜色移动盒子动画
问题描述
我正在尝试创建一个由用户确定速度和颜色的盒子动画。
在这里,JavaScript 每秒查看单选按钮以更新速度和颜色。
速度和颜色单选按钮面板和框应如下所示:
到目前为止,我有以下代码:
function radioSet(a, b, c, d = false){
document.body.append(Object.assign(document.createElement("form"), {id: a}));
let e = document.getElementById(a);
for (let i = 0; i < b; i++){
document.getElementById(a).append(
Object.assign(document.createElement("label"),
{textContent: (d) ? c[i] + " " + i : c[i]}),
Object.assign(document.createElement("input"),
{type: "radio", value: (d) ? c[i] + " " + i : c[i], name: "assigned"}), )
}
document.body.append(Object.assign(document.createElement("hr"), {}));
e.addEventListener("input", () => console.log(a + " change! " + e.assigned.value) )
}
radioSet("speed", 51, Array(51).fill("Speed"), true)
radioSet("color", 3, ["red", "yellow", "blue"])
const box = {
width: 15,
left: 0,
end_pos: 80,
dx: 1, // speed, updated by the speed radio button
element: null, // the div
wait: 10, // ms delay, every one second
event_id: null // event id
};
function animate(){
if(box.left + box.width <= box.end_pos){ // within window
box.element.style.left = box.left + "%"; // display
// update position
box.left += box.dx;
box.event_id = setTimeout( animate, box.wait );
}
}
window.addEventListener("load",
()=>{
box.element = document.createElement("div");
document.getElementsByTagName("body")[0].appendChild(box.element);
});
body{
width: 100%;
height: 500px;
position: absolute;
}
div{
width: 40%; /*box width*/
height: 200px; /*box height*/
position: absolute;
top: 300px;
background-color: red; /*box color, updated by the color radio buttons*/
}
到目前为止,我已经创建了这个动画:
在这里,如何根据速度单选按钮更改盒子的速度?
解决方案
推荐阅读
- c# - 通过 IHttpClientFactory 在 DelegatingHandler 中注入值
- java - 如何在没有 java 用户的情况下以 sysdba 身份连接到 oracle 数据库?
- authentication - 从 LDAP 用户标识迁移到 ADFS
- atom-editor - Atom 在新窗口中随机打开文件(而不是在新选项卡中)
- ruby-on-rails - 删除关联后如何保存活动记录对象?
- python - 具有 Maxpooling1D 和 channel_first 的 Keras 模型
- javascript - Vue.js 从另一个数组向一个数组添加一个元素
- ruby-on-rails - 是否可以从同名方法中调用先前定义的方法?
- html - Bootstrap 4 的平滑动画折叠
- c# - C#正则表达式查找所有数字并将它们四舍五入到小数点后两位