創建鼠標可以拖動的DIV

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>自由拖動的DIV層方塊</title>
    <meta http-equiv="content-type" content="text/html;charset=gb2312" />
    <style type="text/css">
        #draggable
        {
            background-color: green;
            font-size: 9pt;
            padding: 30px;
            color: white;
            width: 360px;
            height: 324px;
            position: absolute;
        }
    </style>

    <script type="text/javascript">
        var rDrag = {

            o: null,

            init: function(o) {
                o.onmousedown = this.start;
            },
            start: function(e) {
                var o;
                e = rDrag.fixEvent(e);
                //取消瀏覽器的默認行爲
                e.preventDefault && e.preventDefault();
                rDrag.o = o = this;
                o.x = e.clientX - rDrag.o.offsetLeft;
                o.y = e.clientY - rDrag.o.offsetTop;
                document.onmousemove = rDrag.move;
                document.onmouseup = rDrag.end;
            },
            move: function(e) {
                e = rDrag.fixEvent(e);
                var oLeft, oTop;
                oLeft = e.clientX - rDrag.o.x;
                oTop = e.clientY - rDrag.o.y;
                rDrag.o.style.left = oLeft + 'px';
                rDrag.o.style.top = oTop + 'px';
            },
            end: function(e) {
                e = rDrag.fixEvent(e);
                rDrag.o = document.onmousemove = document.onmouseup = null;
            },
            fixEvent: function(e) {
                if (!e) {
                    e = window.event;
                    e.target = e.srcElement;
                    //FF的layer是相對於元素的左上角
                    e.layerX = e.offsetX;
                    e.layerY = e.offsetY;
                }
                return e;
            }
        }
        window.onload = function() {
            var obj = document.getElementById('draggable');
            rDrag.init(obj);
        }
    </script>

</head>
<body>
    <div id="draggable">
        這個可以拖動!
        <div style="background-color: blue; height: 300px;">
        
        </div>
    </div>
</body>
</html>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章