js在一個div里面移動其子div


        var ChildDiv = $("#cid");
            var width = 0;  //鼠標點擊子div的地方和子div的左邊邊距距離
            var height = 0;  //鼠標點擊子div的地方和子div的上邊邊距距離
            ChildDiv.onmousedown = function (ev) //鼠標按下DIV
            {
                var ChildDivEvent = ev || event;   //捕獲點擊的對象
                width = ChildDivEvent.clientX - ChildDiv.offsetLeft;
                height = ChildDivEvent.clientY - ChildDiv.offsetTop;
                document.onmousemove = function (ev)   //鼠標移動
                {
                    var ChildDivEvent = ev || event;
                    var x = ChildDivEvent.clientX - width;
                    var y = ChildDivEvent.clientY - height;
                    if (x < 0) //當DIV的Left小於0,也就是移出左邊
                    {
                        x = 0; //就把DIV的Left設置為0,就不能移出左邊
                    } else if (x > $("#pid").width() - ChildDiv.offsetWidth) //DIV不能移出父DIV的右邊
                    {
                        x = $("#pid").width() - ChildDiv.offsetWidth;
                    }
                    if (y < 0) //上邊
                    {
                        y = 0;
                    } else if (y > $("#pid").height() - ChildDiv.offsetHeight) //下邊
                    {
                        y = $("#pid").height() - ChildDiv.offsetHeight;
                    }
                    ChildDiv.style.left = x + 'px'; //DIV的Left設置為新鼠標X坐標減去width的值
                    ChildDiv.style.top = y + 'px'; //DIV的Top設置為新鼠標Y坐標減去height的值
                };
                document.onmouseup = function () //鼠標松開時
                {
                    document.onmousemove = null; //把鼠標移動清除
                    document.onmouseup = null; //把鼠標松開清除
                };
                return false;
            };

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM