JavaScript实现div拖拽吸附效果

JavaScript学习记录

利用JavaScript实现拖拽吸附效果


<html>
<head>
<meta charset="UTF-8">
<title>拖拽title>
<style>
#div1 {
    width: 100px;
    height: 100px;
    background: red;
    position: absolute;
}
style>
<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;
        /*处理浏览器兼容问题*/
        if(oDiv.setCapture)
        {
            oDiv.onmousemove=mouseMove;
            oDiv.onmouseup=mouseUp;
            oDiv.setCapture();
        }
        else
        {
            document.onmousemove=mouseMove;
            document.onmouseup=mouseUp;
        }
        function mouseMove(ev)
        {
            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))
                {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';
            oDiv.style.top=t+'px';  
        }

        function mouseUp()
        {
            this.onmousemove=null;
            this.onmouseup=null;
            if(this.releaseCapture)
            {
                this.releaseCapture();
            }
        }

        return false;
        };
};
script>
head>

<body>
<div id="div1">div>
body>
html>

你可能感兴趣的:(javascript)