JS错误记录 - 事件 - 拖拽

<script>

    window.onload = function()
    {
        var oDiv = document.getElementById('div1');

        var disX = 0; // 为什么在这里声明, 且声明变量为 0 ?
        var disY = 0;

        oDiv.onmousedown = function(ev) 
        // 不是点击整个窗口时拖拽, 是点击div的时候拖拽
        {
            var oEvent = ev || event;
            
            disX = oEvent.clientX - oDiv.offsetLeft;
            disY = oEvent.clientY - oDiv.offsetTop;

            //window.onmousemove = function(ev)  // window.onmouseove 和 document.onmousemove 区别?
            document.onmousemove=function (ev)
            {
                var oEvent = ev || event;
                var l = oEvent.clientX - disX   // 变量表示div位置的值
                var t = oEvent.clientY - disY

                // 画图,分成 左边顶格, 右边顶格 两种情况考虑。
                if(l<0)
                {
                    l=0;
                }    //;  // if 和 else if之间的语句不可以写分号 ; 
                
                else if(l>document.documentElement.clientWidth - oDiv.offsetWidth)
                {
                    l = document.documentElement.clientWidth - oDiv.offsetWidth;
                };

                if(t<0)
                {
                    t=0;
                }
                else if(t>document.documentElement.clientHeight-oDiv.offsetHeight)
                {
                    t=document.documentElement.clientHeight-oDiv.offsetHeight;
                }

                oDiv.style.left = l + 'px'; // left 值有px
                oDiv.style.top =  t + 'px';
            };

            document.onmouseup=function ()
            {
                document.onmousemove=null;
                document.onmouseup=null;
            };

            return false; // 阻止默认事件,解决火狐浏览器拖拽空div的bug
        };    
    };
    </script>

猜你喜欢

转载自www.cnblogs.com/carpenterzoe/p/10214067.html
今日推荐