码迷,mamicode.com
首页 > 其他好文 > 详细

在一个指定的div中拖拽

时间:2015-09-12 10:47:04      阅读:199      评论:0      收藏:0      [点我收藏+]

标签:

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <style>
    #div1
    {
        width: 100px;
        height: 100px;
        background: red;
        position: absolute;
    }
        #div2
        {
            width: 400px;
            height: 300px;
            background: #cccccc;
        }
    </style>
    <script type="text/javascript">
        window.onload = function ()
        {
        var oDiv= document.getElementById(div1);
            var oDiv2 = document.getElementById(div2);
            var disX = 0;
            var disY =0;
            oDiv.onmousedown = function (ev)
            {
                var oEvent = ev||event;

               disX =  oEvent.clientX-oDiv.offsetLeft;
                disY = oEvent.clientY-oDiv.offsetTop;
                document.onmousemove = function (ev)
                {
                    var oEvent = ev||event;
                    var l = oEvent.clientX-disX;
                    var t = oEvent.clientY-disY;
                    if(l<oDiv2.offsetLeft)
                    {
                        l = oDiv2.offsetLeft;
                    }
                    else if(l>oDiv2.offsetWidth-oDiv.offsetWidth+oDiv2.offsetLeft)
                    {
                        l = oDiv2.offsetWidth-oDiv.offsetWidth+oDiv2.offsetLeft;
                    }
                    if(t<oDiv2.offsetTop)
                    {
                        t=oDiv2.offsetTop;
                    }
                    else if(t>oDiv2.offsetHeight-oDiv.offsetHeight+oDiv2.offsetTop)
                    {
                        t =oDiv2.offsetHeight -oDiv.offsetHeight+oDiv2.offsetTop;
                    }
                    oDiv.style.left = l +px;
                    oDiv.style.top =t +px;
                };
                document.onmouseup = function ()
                {
                    document.onmousemove = null;
                    document.onmouseup = null;
                };

            }
        }


    </script>
</head>
<body>
<div id="div2">
    <div id="div1"></div>
</div>

</body>
</html>

 

在一个指定的div中拖拽

标签:

原文地址:http://www.cnblogs.com/zhuni/p/4802642.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!