js--事件对象的理解5-

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<style>
#div1 {100px; height:100px; background:red; position:absolute;}
</style>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>拖曳</title>
<script>
window.onload=function ()
{
    var oDiv=document.getElementById('div1');
    
    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)    //document.onmousemove  给document加事件,防止鼠标快速拖动时 ,鼠标不在移动区域。
        {
            var oEvent=ev||event;
            var l=oEvent.clientX-disX;      //左边距变量
            var t=oEvent.clientY-disY;        //右边距变量
            
            if(l<0)
            {
                l=0;
            }
            else if(l>document.documentElement.clientWidth-oDiv.offsetWidth) //页面的可视区大小-div的left值=div左边距距离
            {
                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;  //页面的可视区高度-div的top值=div上边距距离
            }
            
            oDiv.style.left=l+'px';
            oDiv.style.top=t+'px';
        };
        
        document.onmouseup=function ()
        {
            document.onmousemove=null;
            document.onmouseup=null;
        };
        
        return false;   //阻止火狐 二次拖曳出禁止符号的 默认事件
    };
};  //浏览器重置的时候 会有问题,在BOM onresize时补充
</script>
</head>

<body>
<div id="div1"></div>
</body>
</html>
原文地址:https://www.cnblogs.com/lanyueff/p/4607157.html