原生js小球运动

时间:2024-10-12 08:05:31

//html代码

<input type="button" value="小球运动" />

<div></div>

//js代码

var btn = document.getElementsByTagName("input")[0];

var ball = document.getElementsByTagName("div")[0];

var speedX = 10;

var speedY = 10;

var timer = null;

btn.onclick = function(){

  clearInterval(timer);

  timer = setInterval(function(){

    ball.style.left = ball.offsetLeft + speedX + "px";

    ball.style.top = ball.offsetTop + speedY + "px";

    var x = window.innerWidth - ball.offsetWidth;

    var y = window.innerHeight - ball.offsetHeight;

    //边界检测

    if( ball.offsetLeft <= 0 ){

      speedX *= -1;

    }else if( ball.offsetLeft >= x ){

      ball.style.left = x + "px";

      speedX *= -1;

    } 

    

    if( ball.offsetTop <= 0 ){

      speedY *= -1;

    }else if( ball.offsetTop >= x ){

      ball.style.top = y + "px";

      speedY *= -1;

    } 

  },10)

}