js重力球效果代码实例

快乐打工仔 分类:实例代码

分享一段代码实例,它利用js实现了重力球效果。

本例子中,用鼠标向下拖动小球,然后松开即可查看演示。

代码实例如下:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.pipipi.net/" />
<title>犀牛前端部落</title>
<style>
* {
  margin: 0px;
  padding: 0px;
}
#div1 {
  width: 50px;
  height: 50px;
  background: pink;
  position: absolute;
  cursor: pointer;
  border-radius: 50px;
}
div {
  width: 3px;
  height: 3px;
  background: black;
  position: absolute;
}
</style>
<script>
window.onload = function() {
  var oDiv = document.getElementById('div1');
  //拖曳
  var lastX = 0;
  var lastY = 0;
  oDiv.onmousedown = function(ev) {
    var ev = ev || event;
    var disX = ev.pageX - oDiv.offsetLeft;
    var disY = ev.pageY - oDiv.offsetTop;
    document.onmousemove = function(ev) {
      var ev = ev || event;
      var l = ev.pageX - disX;
      var t = ev.pageY - disY;
      oDiv.style.left = l + 'px';
      oDiv.style.top = t + 'px';
      iSpeedX = l - lastX;
      iSpeedY = t - lastY;
      lastX = l;
      lastY = t;
    }
    document.onmouseup = function() {
      document.onmousemove = null;
      document.onmouseup = null;
      startMove();
    }
    clearInterval(timer);
  }
  var timer = null;
 
  function startMove() {
    var nowX = oDiv.offsetLeft;
    var nowY = oDiv.offsetTop;
    clearInterval(timer);
    timer = setInterval(function() {
      iSpeedY += 3
      nowX += iSpeedX;
      if (nowX > document.documentElement.clientWidth - oDiv.offsetWidth) {
        iSpeedX *= -0.8;
        nowX = document.documentElement.clientWidth - oDiv.offsetWidth;
      } else if (nowX < 0) {
        iSpeedX *= -0.8;
        nowX = 0;
      }
      nowY += iSpeedY;
      if (nowY > document.documentElement.clientHeight - oDiv.offsetHeight) {
        iSpeedY *= -0.8;
        iSpeedX *= 0.8
        nowY = document.documentElement.clientHeight - oDiv.offsetHeight;
      } else if (nowY < 0) {
        iSpeedY *= -1;
        iSpeedX *= 0.8;
        nowY = 0;
      }
      if (Math.abs(iSpeedX) < 1) {
        iSpeedX = 0;
      }
      if (Math.abs(iSpeedY) < 1) {
        iSpeedY = 0;
      }
      if (iSpeedX == 0 && iSpeedY == 0 && nowY == document.documentElement.clientHeight - oDiv.offsetHeight) {
        clearInterval(timer);
      }
      oDiv.style.left = nowX + 'px';
      oDiv.style.top = nowY + 'px';
    }, 30)
  }
}
</script>
</head>
<body>
<div id='div1'></div>
</body>
</html>

js重力球效果代码实例,这样的场景在实际项目中还是用的比较多的,关于js重力球效果代码实例就介绍到这了。

js重力球效果代码实例属于前端实例代码,有关更多实例代码大家可以查看

回复

我来回复
  • 暂无回复内容