欢迎访问我的博客 https://javascript.shop

javascript实现可拖动DIV层

原文发布时间为:2009-05-04 —— 来源于本人的百度文章 [由搬家工具导入]

注意以下红色部分是关键.如果不使用      document.documentElement,而使用document.body,则在FF会出现问题;如果不使用background:red; 样式,则在IE中会出现只有当鼠标放在DIV边框上时才能拖动.

        var offset_x;
        var offset_y;
        function Milan_StartMove(oEvent)
        {
            var whichButton;
            if(document.all&&oEvent.button==1) whichButton=true;
            else { if(oEvent.button==0)whichButton=true;}
            if(whichButton)
            {
                var oDiv=document.getElementById("oDiv");
                offset_x=parseInt(oEvent.clientX-oDiv.offsetLeft);
                offset_y=parseInt(oEvent.clientY-oDiv.offsetTop);
                document.documentElement.onmousemove=function(mEvent)
                {   
                    var eEvent;
                    if(document.all) eEvent=event;
                    else{eEvent=mEvent;}
                    var oDiv=document.getElementById("oDiv");
                    var x=eEvent.clientX-offset_x;
                    var y=eEvent.clientY-offset_y;
                    oDiv.style.left=(x)+"px";
                    oDiv.style.top=(y)+"px";
                }
            }
        }
        function Milan_StopMove(oEvent){document.documentElement.onmousemove=null; }

<div id="oDiv" onmousedown="Milan_StartMove(event)" onmouseup="Milan_StopMove(event)" style="cursor:move;position:absolute;width:100px;height:60px;border:1px solid silver;left:100px;top:100px;background:white;z-index:9999;">
        </div>

以上为跨IE6和FF浏览器的解决方案,理清思路后,做起来相当简单.

注意:移动到页面外部将出现问题。。。

posted @ 2017-07-12 00:05  孑孓子  阅读(96)  评论(0编辑  收藏  举报
欢迎访问我的博客 https://javascript.shop