JavaScript元素上下弹性运动

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

JavaScript元素上下弹性运动属于前端实例代码,有关更多实例代码大家可以查看

分享一段代码实例,它实现了元素上下弹性运动效果,类似于一个小球能够上下弹动的现象。

代码实例如下:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.pipipi.net/" />
<title>前端教程网</title>
<style>
body {
  margin: 0;
  padding: 0;
}
#box {
  width: 50px;
  height: 50px;
  background: red;
  position: absolute;
  left: 0;
  top: 0;
  margin: 0;
}
</style>
<script>
window.onload = function() {
  oDiv = document.getElementById('box');
  var l = 0;
  var t = 0;
  var ispeedX = 0;
  var ispeedY = 0;
  var timer = null;
  oDiv.onmousedown = function(ev) {
    clearInterval(timer);
    var ev = ev || event;
    var disX = ev.clientX - oDiv.offsetLeft;
    var disY = ev.clientY - oDiv.offsetTop;
    document.onmousemove = function(ev) {
        var ev = ev || event;
        oDiv.style.left = ev.clientX - disX + 'px';
        oDiv.style.top = ev.clientY - disY + 'px';
 
        ispeedX = oDiv.offsetLeft - l;
        ispeedY = oDiv.offsetTop - t;
        l = oDiv.offsetLeft;
        t = oDiv.offsetTop;
      } //onmousemove
 
    document.onmouseup = function() {
      document.onmousemove = null;
      clearInterval(timer);
      boomMove(oDiv);
 
      function boomMove(obj) {
 
        var clientX = document.documentElement.clientWidth - obj.offsetWidth || document.body.clientWidth - obj.offsetWidth;
        var clientY = document.documentElement.clientHeight - obj.offsetHeight || document.body.clientHeight - obj.offsetHeight;
 
        timer = setInterval(function() {
 
          ispeedY += 3;
 
          var x = obj.offsetLeft + ispeedX;
          var t = obj.offsetTop + ispeedY;
 
 
 
          if (x > clientX) {
            x = clientX;
            ispeedX *= -1;
          };
          if (x < 0) {
            x = 0;
            ispeedX *= -1;
          };
          if (t > clientY) {
            t = clientY;
 
            ispeedY *= -0.8;
            ispeedX *= 0.9;
          };
          if (t < 0) {
            t = 0;
            ispeedY *= -1
          };
 
 
          obj.style.left = x + 'px';
          obj.style.top = t + 'px';
 
          if (Math.abs(ispeedX) < 1) {
            ispeedX = 0;
          };
          if (Math.abs(ispeedY) < 1) {
            ispeedY = 0;
          };
          if (ispeedX == 0 && ispeedY == 0 && oDiv.offsetTop == clientY) {
            clearInterval(timer);
          }
 
        }, 30);
      }
    }
  }
}
</script>
</head>
<body>
<div id="box"></div>
</body>
</html>

JavaScript元素上下弹性运动,这样的场景在实际项目中还是用的比较多的,关于JavaScript元素上下弹性运动就介绍到这了。

回复

我来回复
  • 暂无回复内容