zoukankan      html  css  js  c++  java
  • 如何用JavaScript做一个可拖动的div层

    可拖动的层在Web设计中用处很多,比如在某些需要自定义风格布局的应用中,控件就需要拖动操作,下面介绍一个,希望可以满足你的需求,顺便学习一下可拖动的层是如何实现的。

    下面是效果演示:

    这个DIV可以移动,你可以测试下。
     

    JavaScript code

    <script type="text/javascript">
    // <![CDATA[
    var $j=function(id){return document.getElementById(id);};
    var getMouseP=function (e){
    	//获取鼠标坐标 请传递evnet参数
    	e = e || window.event;
    	var m=(e.pageX || e.pageY)?{ x:e.pageX, y:e.pageY } : { x:e.clientX + document.body.scrollLeft - document.body.clientLeft, y:e.clientY + document.body.scrollTop  - document.body.clientTop };
    	return m;
    };
        
    move=function(o,t){
    	o=$j(o);
    	t=$j(t);
    	o.onmousedown=function(ev){
    		var mxy=getMouseP(ev);//获取当前鼠标坐标
    		var by={x:mxy.x-(t.offsetLeft),y:mxy.y-(t.offsetTop)};
    		o.style.cursor="move";
    		document.onmousemove=function(ev){
    			var mxy=getMouseP(ev);
    			t.style.left=mxy.x-by.x+"px";
    			t.style.top=mxy.y-by.y+"px";
    		};
    		document.onmouseup=function(){
    			window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty();
    			this.onmousemove=null;
    		}
    	}
    }
    move("jelle_test_div","jelle_test_div");
    // ]]>
    </script>
  • 相关阅读:
    期待Eclipse3.4
    Winforms中使用系统托盘图标
    Eclipse下的Struts2开发插件
    彩色 夺冠
    网络&系统
    A Famous Music Composer
    Quick Brown Fox
    解密QQ号——队列
    谁先倒
    bootstrap Table从零开始
  • 原文地址:https://www.cnblogs.com/xiaoyang002/p/4069154.html
Copyright © 2011-2022 走看看