首页 > 解决方案 > 如何以速度和颜色移动盒子动画

问题描述

我正在尝试创建一个由用户确定速度和颜色的盒子动画。

在这里,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*/
}

到目前为止,我已经创建了这个动画:

在此处输入图像描述

在这里,如何根据速度单选按钮更改盒子的速度?

标签: javascriptanimation

解决方案


推荐阅读