• 案例——拖拽


    拖拽

    <!DOCTYPE html>
    <html>
    	<head>
    		<meta charset="utf-8">
    		<title></title>
    		<style type="text/css">
    			#box1{
    				 100px;
    				height: 100px;
    				background-color: skyblue;
    				position: absolute;
    			}
    			#box2{
    				 100px;
    				height: 100px;
    				background-color: yellow;
    				position: absolute;
    				left: 200px;
    				top: 200px;
    			}
    		</style>
    		<script type="text/javascript">
    			window.onload=function(){
    				/*
    				拖拽box1元素
    				 - 拖拽的流程
    				     1.当鼠标在被拖拽元素上按下时,开始拖拽  onmousedown
    					 2.当鼠标移动时被拖拽元素跟随鼠标移动  onmousemove
    					 3.当鼠标松开时,被拖拽元素固定在当前位置 onmouseup
    				*/
    			   
    			   // 获取box1?
    			   var box1=document.getElementById("box1");
    			   // 为box1绑定一个鼠标按下事件
    			   box1.onmousedown=function(event){
    				   // div的偏移量  鼠标.clientX - 元素.offsetLeft
    				   // div的偏移量  鼠标.clentY -元素.offsetTop
    				   event = event || window.event;
    				   var ol=event.clientX - box1.offsetLeft;
    				   var ot=event.clientY-box1.offsetTop;
    				   
    				   // 为document绑定一个onmousemove事件
    				   document.onmousemove=function(event){
    					   event = event || window.event;
    					   // 当鼠标移动时被拖拽元素跟随鼠标移动  onmousemove
    					   // 获取鼠标坐标?
    					   var left =event.clientX - ol;
    					   var top=event.clientY - ot;
    					   
    					   // 修改box1的位置
    					   
    					   box1.style.left=left+"px";
    					   box1.style.top=top+"px";
    				   }
    				    // 当鼠标松开时,被拖拽元素固定在当前位置 onmouseup
    				   document.onmouseup=function(){
    				   				   // 取消document.onmousemove事件
    				   				   document.onmousemove=null;
    				   				   
    				   				   document.onmouseup=null;
    				   				   alert(12);
    				   }
    			   };
    			  /*
    			  当我们拖拽一个网页中的内容时,浏览器会默认去搜索引擎中搜索内容
    			  此事后导致拖拽功能的异常
    			  如果不希望发生这个异常   return false
    			  
    			  对IE8不起作用
    			  */
    			  return false;
    			}
    		</script>
    	</head>
    	<body>
    		<div id="box1"></div>
    		<div id="box2"></div>
    	</body>
    </html>
    
    
  • 相关阅读:
    Atcoder Grand Contest 003 题解
    Atcoder Grand Contest 002 题解
    Atcoder Grand Contest 001 题解
    网络流24题
    AGC005D ~K Perm Counting
    loj6089 小Y的背包计数问题
    CF932E Team Work
    组合数学相关
    SPOJ REPEATS
    [SDOI2008]Sandy的卡片
  • 原文地址:https://www.cnblogs.com/SSPOFA/p/12057497.html
Copyright © 2020-2023  润新知