js重力球效果代碼實例

分享一段代碼實例,它利用js實現了重力球效果。

本例子中,用鼠標向下拖動小球,然後鬆開即可查看演示。

代碼實例如下:

001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
062
063
064
065
066
067
068
069
070
071
072
073
074
075
076
077
078
079
080
081
082
083
084
085
086
087
088
089
090
091
092
093
094
095
096
097
098
099
100
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<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>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章