我们先来看下之前的运动的代码,是否支持多物体运动,会出现怎么样的问题。

复制代码 代码如下:
<style type="text/css">
            div {
                width: 100px;
                height: 50px;
                background: red;
                margin: 10px;
            }
        </style>

复制代码 代码如下:
<body>
        <div></div>
        <div></div>
        <div></div>
    </body>

以下是Javascript 代码:

复制代码 代码如下:
<script type="text/javascript">
            window.onload = function() {
                var aDiv = document.getElementsByTagName('div');
                for (var i = 0; i < aDiv.length; i++) {
                    aDiv[i].onmouseover = function() {
                        startMove(this, 400);
                    };
                    aDiv[i].onmouseout = function() {
                        startMove(this, 100);
                    };
                }
            }
            var timer = null;
            function startMove(obj, iTarget) {
                clearInterval(timer);
                timer = setInterval(function() {
                    var speed = (iTarget - obj.offsetWidth) / 6;
                    speed = speed > 0 "codetitle">复制代码 代码如下:
<script type="text/javascript">
            window.onload = function() {
                var aDiv = document.getElementsByTagName('div');
                for (var i = 0; i < aDiv.length; i++) {
                    aDiv[i].timer=null; // 把定时器作为一个物体的属性存起来
                    aDiv[i].onmouseover = function() {
                        startMove(this, 400);
                    };
                    aDiv[i].onmouseout = function() {
                        startMove(this, 100);
                    };
                }
            }
            function startMove(obj, iTarget) {
                clearInterval(obj.timer);
                obj.timer = setInterval(function() {
                    var speed = (iTarget - obj.offsetWidth) / 6;
                    speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed);
                    if (obj.offsetWidth == iTarget) {
                        clearInterval(obj.timer);
                    } else {
                        obj.style.width = obj.offsetWidth + speed + 'px';
                    }
                }, 30);
            }
        </script>

这样程序就没有问题了,能够支持多物体的运动。

华山资源网 Design By www.eoogi.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
华山资源网 Design By www.eoogi.com