之前的模块代码太死板了,由于内部定义了控件的ID,使用起来很不方便,so-----直接看代码

<script>
    var move =(function(){
        function drop(bar,target){
            var target=document.getElementById(target),bar=document.getElementById(bar);
            bar.onmousedown=drag;
            function drag(event){
                event=event||window.event;
                var ox=event.clientX-target.offsetLeft,oy=event.clientY-target.offsetTop;
                document.onmousemove=function(event){
                    event=event||window.event;
                    var oh=document.documentElement.clientHeight,ow=document.documentElement.clientWidth,
                    maxy=oh-target.offsetHeight,maxx=ow-target.offsetWidth;
                    var x=event.clientX-ox,y=event.clientY-oy;
                    if(x<0)x=0;
                    else if(x>maxx)x=maxx;
                    if(y<0)y=0;
                    else if(y>maxy)y=maxy;
                    target.style.left=x+"px";
                    target.style.top=y+"px";
                };
                document.onmouseup=function(){
                    document.onmousemove=null;
                    document.onmouseup=null;
                };
            }
        }
        return{
            go:drop
        }
    })();
    </script>

乍一看,与之前的区别就是双引号放在模块里面和模块外面的区别;

看这里:getElementByID(”bar”)和getElementByID(bar);

前者只能获得ID名为#bar的控件,而后者可以获得任意ID名的控件(你想传啥就传啥,传不进来算我输!);

所以,优化之后的模块适用于任意控件的拖拽;

统一方法:move.go("获得鼠标点击事件的控件ID","你想移动的控件ID");

例如我定义了两个控件ID:div1和div2---方法:move.go("div1","div2"),

至此,over!

小贴士:被移动的控件必须position:absolute;这个和模块无关,属于常识TT

相关文章:

  • 2022-12-23
  • 2022-01-02
  • 2021-12-22
  • 2022-02-02
  • 2022-12-23
  • 2019-01-15
猜你喜欢
  • 2022-01-26
  • 2022-12-23
  • 2021-07-25
  • 2021-11-09
  • 2022-01-05
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案