javascript链式运动框架案例

javascript链式运动框架

任务描述:

当鼠标移入红色矩形时,该矩形宽度逐渐增加至400px,之后高度逐渐增加至400px;

当鼠标移出红色矩形时,该矩形高度逐渐减小至200px,之后宽度逐渐减小至200px。

效果图:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <title>JS小案例:多物体变宽</title>
  <style>
    body {
      height: 2000px;
      margin: 0px;
    }

    div {
       200px;
      height: 200px;
      background: red;
      margin: 10px;
    }
  </style>
  <script>
    window.onload = function () {
     
      //补充代码
    }
  </script>
</head>

<body>
  <div id='div1'></div>
</body>

</html>

  

参考代码:

oDiv1 = document.getElementById('div1');

oDiv1.onmouseover = function () {
    startMove(oDiv1, 'width', 400, function () {
        startMove(oDiv1, 'height', 400)
    });
}

oDiv1.onmouseout = function () {
    startMove(oDiv1, 'height', 200, function () {
        startMove(oDiv1, 'width', 200)
    });
}


function getStyle(obj, name) {

    if (obj.currentStyle) {

        return obj.currentStyle[name];
    }
    else {

        return getComputedStyle(obj, null)[name];
    }
}



function startMove(obj, attr, iTarget, fnEnd) {

    clearInterval(obj.timer);

    obj.timer = setInterval(function () {

        var cur = 0;

        if (attr == 'opacity') {

            //Math.round()四舍五入取整主要是针对低浮点数的精度问题。
            cur = Math.round(parseFloat(getStyle(obj, attr)) * 100);

        } else {

            cur = parseInt(getStyle(obj, attr));
        }

        var speed = (iTarget - cur) / 6;

        speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed);


        if (cur == iTarget) {

            clearInterval(obj.timer);

            if (fnEnd) {
                fnEnd();
            }

        } else {

            if (attr == 'opacity') {

                obj.style.opacity = (cur + speed) / 100;

                obj.style.filter = 'alpha(opacity=' + (cur + speed) + ")";



            }

            else {

                obj.style[attr] = cur + speed + 'px';

            }

        }

    }, 30)

}

  

原文地址:https://www.cnblogs.com/f6056/p/11339067.html