简单的拖拽效果封装实例

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>js</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, 
user-scalable=no"/>
<style>
*{margin: 0;padding: 0;}
#div1{
	width: 100px;
	height: 100px;
	background: red;
	position: absolute;
}
</style>
</head>
<script type="text/javascript">
	window.onload = function(){
		var oDiv = document.getElementById('div1');
		drag(oDiv);
		function drag(obj){
			obj.onmousedown = function(event){
			var disX = event.clientX - this.offsetLeft;
			var disY = event.clientY - this.offsetTop;
			document.onmousemove = function(event){
				var L = event.clientX - disX ;
				var T = event.clientY - disY ;

				/*if(L < 0){// L<80 为磁性吸附效果
					L = 0;
				}else if(L > document.documentElement.clientWidth - obj.offsetWidth){
					L = document.documentElement.clientWidth - obj.offsetWidth;
				}
				if(T < 0){
					T = 0;
				}else if(T > document.documentElement.clientHeight - obj.offsetHeight){
					T = document.documentElement.clientHeight - obj.offsetHeight;
				}  //if这开始为范围拖拽
*/
				obj.style.left = L + 'px';
				obj.style.top = T + 'px';
			}
			obj.onmouseup = function(){
				document.onmousemove= document.onmouseup = null;
			}
			return false;
		}
	}	
}
</script>
<body>
	<div id="div1">
		
	</div>
</body>
</html>

阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/a772116804/article/details/80330310
个人分类: JavaScript
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭