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

复制代码 代码如下:
<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>

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

标签:
Javascript,多物体,运动

免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
狼山资源网 Copyright www.pvsay.com

评论“Javascript 多物体运动的实现”

暂无“Javascript 多物体运动的实现”评论...