原生js小球运动

//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) 

}

 

posted @ 2017-12-23 15:20  凹润之之之  阅读(1302)  评论(0编辑  收藏  举报