日期:2014-05-16  浏览次数:20347 次

不用JQ,两个不同div块 沿着直线移动到重叠
有两个div块,高和宽都是一样大小,但是位置不同,
如何使得单击按钮后,其中一个div块移动到另一个div块的位置(重叠)

求帮忙,谢了

------解决方案--------------------
HTML code

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gbk" />
<title></title>
<style>
    div {
        position:absolute; left: 100px; top:100px;
        width:100px; height:100px;
        border:1px solid red;
    }
</style>
<script type="text/javascript">
var Animate = function (oElement, options, callback) {this.initialize.apply(this, arguments)};

Animate.prototype = {
    initialize: function (oElement, options, callback)
    {
        var oThis = this;
        this.options = options;
        this.callback = callback;
        this.oElement = typeof oElement === "string" ? document.getElementById(oElement) : oElement;
        clearInterval(this.timer);
        this.timer = setInterval(function ()
        {
            oThis.doMove()
        }, 30)
    },
    css: function (attr, value)
    {
        if (arguments.length == 1)
        {
            return parseFloat(this.oElement.currentStyle ? this.oElement.currentStyle[attr] : getComputedStyle(this.oElement, null)[attr])
        }
        else if (arguments.length == 2)
        {
            attr == "opacity" ? (this.oElement.style.filter = "alpha(opacity=" + value + ")", this.oElement.style.opacity = value / 100) : this.oElement.style[attr] = value + "px"
        }
    },
    doMove: function ()
    {
        var opt = this.options;
        var bComplete = true;        
        for (var p in opt)
        {
            var iCur = p == "opacity" ? parseInt(this.css(p).toFixed(2) * 100) : this.css(p);
            var iSpeed = (opt[p] - iCur) / 5;
            iSpeed = iSpeed > 0 ? Math.ceil(iSpeed) : Math.floor(iSpeed);
            opt[p] == iCur || (bComplete = false, this.css(p, iCur + iSpeed))
        }
        bComplete && (clearInterval(this.timer), this.callback && this.callback.call(this))
    }
};
</script>
</head>
<body>
    <div id="a" style="z-index:1;"></div>
    <div style="border-color:blue; left:300px; top:200px; width:200px; height:200px;" id="b"></div>
    <script type="text/javascript">
        function $(el){
            return typeof el == 'string' ? document.getElementById(el) : el;
        }
        var b = $('b')
        var data = {
            width: parseInt(b.style.width),
            height: parseInt(b.style.height),
            left: parseInt(b.style.left),
            top: parseInt(b.style.top)
        };
        new Animate('a', {
            width: data.width,
            height: data.height,
            left: data.left,
            top: data.top
        })
    </script>
</body>
</html>