zoukankan      html  css  js  c++  java
  • javascript拖拽

    <!DOCTYPE html>
    <html lang="en">
    <head>
    	<meta charset="UTF-8">
    	<title>Document</title>
    	<style>
    		#box{
    			100px; 
    			height:100px; 
    			background:blue; 
    			position:absolute; 
    			left:0; 
    			top:0;
    		}
    	</style>
    </head>
    <body>
    	<div id="box">
    		
    	</div>
    
    	<script>
    		window.onload=function(){
    			var oDiv=document.getElementById("box");
    			drag.fn(oDiv);
    		}
    
    		var drag=(function(){
    			// 设置元素拖拽的边界
    			var range=function(inum,imax,imin){
    				if(inum<imin){
    					return imin;
    				}else if(inum>imax){
    					return imax;
    				}else{
    					return inum;
    				}
    			}
    			var fn =function(obj){
    				obj.onmousedown=function(ev){
    					var ev=ev||event;
    					// 阻止浏览器的默认行为(当鼠标按下的时候,如果有文字被选中,那么会触发浏览器默认拖拽文字的效果,如果拖拽的是图片也会触发一些默认的效果)
    					ev.preventDefault();
    					// 获取鼠标按下的时候鼠标的X轴坐标距离元素左边的距离
    					var disX=ev.clientX-obj.offsetLeft;
    					// 获取鼠标按下的时候鼠标的Y轴坐标距离元素上边的距离
    					var disY=ev.clientY-obj.offsetTop;
    					document.onmousemove=function(ev){
    						var ev = ev||event;
    						ev.preventDefault();
    						// 获取元素的left值
    						var L=range(ev.clientX-disX,document.documentElement.clientWidth-obj.offsetWidth,0);
    						// 获取元素的top值
    						var T=range(ev.clientY-disY,document.documentElement.clientHeight-obj.offsetHeight,0);
    						//设置元素的left值
    						obj.style.left=L+"px";
    						// 设置元素的top值
    						obj.style.top=T+"px";
    					}
    					document.onmouseup=function(ev){
    						var ev = ev||event;
    						ev.preventDefault();
    						// 当鼠标按键松开的时候停止鼠标移动事件
    						document.onmousemove=null;
    					}
    				}
    			}
    			return{
    				fn:fn
    			}
    		})()
    	</script>
    </body>
    </html>
    

      

  • 相关阅读:
    Linq To Sql 练习
    伪静态在webconfig中配置
    log4net.dll配置以及在项目中应用
    C#Windows服务安装
    .net平台推送ios消息
    asp.net下js调用session
    MAC地址泛洪攻击测试
    wifipineapple使用教程
    python程序的调试方法
    python import的用法
  • 原文地址:https://www.cnblogs.com/lvruifang/p/7251408.html
Copyright © 2011-2022 走看看