JavaScript implements carnival dancing balls

The ball effect of carnival dancing (that is, an html code):


Code (html):

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Rolling ball</title>
    <style>
        *{
            padding: 0;
            margin: 0;
        }
        body,html{
            height: 100%;
            background-color: navajowhite;
        }
        body{
            position: relative;
        }
        div{
            border-radius: 50%;
            position: absolute;
        }

    </style>
</head>
<body>
<script>
    //The page has 20 balls
    for(var i=0;i<20;i++){
        creatRandomBall (document.body);
    }
    /*
    * div is to make it mirror bounce for each div
    * The function of this function is to achieve the mirror bounce effect of a single div
    * */
    function move(div) {
    //The maximum left and maximum top values ​​required by the div
        var maxleft = div.parentElement.offsetWidth - div.offsetWidth;
        console.log(div.parentElement.offsetWidth);
        var maxtop = div.parentElement.offsetHeight - div.offsetHeight;
        var directionX = 1;
        var directionY = 1;
        var speedX = randomNum(1,5);
        var speedY = randomNum(1,5);

        setTimeout(function step() {
            //Set the properties of the move
            div.style.left = div.offsetLeft + speedX * directionX+"px";
            div.style.top = div.offsetTop + speedY * directionY+"px";
            console.log(div.style.left);
            / / Determine the value of the direction to change the value of the two edges
            //Here div.offsetLeft <= 0 must be less than or equal to 0, I have been looking for more than an hour, so sad
            if(div.offsetLeft >= maxleft || div.offsetLeft <= 0){
                directionX *= -1;
            }
            if(div.offsetTop >= maxtop || div.offsetTop <= 0){
                directionY *= -1;
            }

            setTimeout(step,10);
        },0);
    }
    /*
    * Create an element, random position, random color, random width and height
    * Then pass it to the specified parent container
    * */
    function creatRandomBall(parent) {
        var div = document.createElement("div");
        var wh = randomNum(5,120);
        div.style.width = wh+"px";
        div.style.height = wh+"px";

        div.style.left = randomNum(0,parent.offsetWidth - wh)+"px";
        div.style.top = randomNum(0,parent.offsetHeight - wh)+"px";
        div.style.backgroundColor = "rgba("+randomNum(0,255)+","+randomNum(0,255)+","+randomNum(0,255)+","+Math.random()+")";
        parent.appendChild(div);
        move(div);
    }
    /* The random function is +n at the end */
    function randomNum(n,m) {
        return parseInt(Math.random()*(m-n+1)+n);
    }
</script>
</body>
</html>

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324536996&siteId=291194637