美文网首页
智能社拖拽demo

智能社拖拽demo

作者: jacklin1992 | 来源:发表于2016-12-30 16:37 被阅读26次
<!DOCTYPE HTML>
<html>
<head>
    <meta charset="utf-8">
    <title>无标题文档</title>
    <style>#div1 {
        width: 100px;
        height: 100px;
        background: red;
        position: absolute;
    }

    #div2 {
        width: 400px;
        height: 300px;
        background: #CCC;
        position: relative;
    }</style>
    <script>window.onload = function () {
        var oDiv = document.getElementById('div1');
        var oDiv2 = document.getElementById('div2');
        var disX = 0;
        var disY = 0;
        oDiv.onmousedown = function (ev) {   //4 放在里面
            var oEvent = ev || event;
            disX = oEvent.clientX - oDiv.offsetLeft;
            disY = oEvent.clientY - oDiv.offsetTop;
            document.onmousemove = function (ev) { //3
                var oEvent = ev || event;
                var l = oEvent.clientX - disX;
                var t = oEvent.clientY - disY;
                if (l < 0) {
                    l = 0;
                } else if (l > oDiv2.offsetWidth - oDiv.offsetWidth) {
                    l = oDiv2.offsetWidth - oDiv.offsetWidth;
                }
                if (t < 0) {
                    t = 0;
                } else if (t > oDiv2.offsetHeight - oDiv.offsetHeight) {
                    t = oDiv2.offsetHeight - oDiv.offsetHeight;
                }
                  oDiv.style.left = l + 'px';
           oDiv.style.top = t + 'px';
            };
            document.onmouseup = function () {
                document.onmousemove = null;//2
                document.onmouseup = null;
            };
            return false;//1
        };
    };</script>
</head>
<body>
<div id="div2">
    <div id="div1"></div>
</div>
</body>
</html>

相关文章

网友评论

      本文标题:智能社拖拽demo

      本文链接:https://www.haomeiwen.com/subject/nlimvttx.html