JS-案例-div自动右下左上移动(随机变色)

论坛 期权论坛 编程之家     
选择匿名的用户   2021-6-2 20:31   1342   0
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        html,body{margin:0;padding:0;}
        div{
            width: 100px;
            height: 100px;
            background-color: aqua;
            position: absolute;
        }
    </style>
</head>
<body>
<div></div>
    <script>
        var dirc="right";
        var bool=true;
        init();//构造初始化函数,添加点击事件
        function init() {
            var div=document.querySelector("div");
            document.addEventListener("click",clickHandler);
            setInterval(animation,41,div)//添加每个41ms(帧频24)执行一次的函数
        }
        function clickHandler(e) {
            bool=!bool;//达到点击鼠标停止,再次点击,继续移动的效果(开关)
        }

        function animation(div) {
            if (!bool) return;
            var str="rgba(";
            for (var i=0;i<3;i++){
                str+=Math.floor(Math.random()*256)+","
            }
                str+=Math.random().toFixed(2)+")";
            div.style.backgroundColor=str;//随机颜色
            switch (dirc){
                case "right":
                    div.style.left=div.offsetLeft+5+"px";
                    if (div.offsetLeft>1178){
                        dirc="bottom";
                    }
                    break;//控制div向右移动到1178时,跳出,然后执行下一次的dirc
                case "bottom":
                    div.style.top=div.offsetTop+5+"px";
                    if (div.offsetTop>584){
                        dirc="left"
                    }
                    break;//控制div向下移动到584时,跳出,然后执行下一次的dirc
                case "left":
                    div.style.left=div.offsetLeft-5+"px";
                    if (div.offsetLeft<=0){
                        dirc="top"
                    }
                    break;//控制div向左移动到0时,跳出,然后执行下一次的dirc
                case "top":
                    div.style.top=div.offsetTop-5+"px";
                    if (div.offsetTop<=0){
                        dirc="right"
                    }
                    break;//控制div上右移动到0时,跳出,然后执行下一次的dirc
            }

        }
    </script>
</body>
</html>

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP