js模封装仿重力场方法

重力场

  • 一、实现

一、实现

var timer;
function gravity(dom){
    clearInterval(dom.timer);
    var g = 10,//重力加速度
    speedX = 5,//初速度
    speedY = 10;
    dom.timer = setInterval(function(){
        speedY +=g;
        var newTop = dom.offsetTop + speedY;//计算当前位置
        var newLeft = dom.offsetLeft + speedX;
        if(newTop >=document.documentElement.clientHeight - dom.clientHeight){
            speedY *=-1;//到达界限速度反向
            speedX *= 0.8;//动能损耗
            speedY *= 0.8;
            newTop = document.documentElement.clientHeight - dom.clientHeight - 1;
            //将界限值赋予当前高度,防止出现滚动条(多减了1)
        };
        if(newTop <=0){
            speedY *=-1;
            speedX *= 0.8;
            speedY *= 0.8;
            newTop = 0;
        };
        if(newLeft >=document.documentElement.clientWidth - dom.clientWidth){
        	speedX *=-1;
            speedX *= 0.8;
            speedY *= 0.8;
            newLeft = document.documentElement.clientWidth - dom.clientWidth - 1;    
        };
        if(newLeft <=0){
            speedX *=-1;
            speedX *= 0.8;
            speedY *= 0.8;
            newLeft = 0;
        };
        if(Math.abs(speedX) < 1){
            speedX = 0;
        };
        if(Math.abs(speedY) < 1){
            speedY = 0;
        };
        if(speedX == 0 && speedY == 0 && newTop == document.documentElement.clientWidth - dom.clientWidth - 1){
            clearInterval(dom.timer);
           	//判断是否静止
        }else{
            dom.style.left = newLeft + 'px';
            dom.style.top = newTop + 'px';
        };
    },50);
};

你可能感兴趣的:(JavaScript的学习)