原生JS DIV拖拽效果

效果图

html

<!DOCTYPE html>
<html>
<head>
	<title></title>
	<meta charset="utf-8">
	<style type="text/css">
	*{
		margin: 0;
		padding: 0;
	}
	.box-hd{
		width: 300px;
		height: 230px;
		position: absolute;
		left: 0;
		top: 0;
		background: #000;
		-webkit-box-shadow: 0 0 10px rgba(125,125,125,0.8);
	    -moz-box-shadow: 0 0 10px rgba(125,125,125,0.8);
	    box-shadow: 0 0 10px rgba(125,125,125,0.8);
	    border-radius: 4px;
	}
	.box-hd  h2{
		border-top-left-radius: 4px;
		border-top-right-radius: 4px;
		padding: 0 15px;
		color: #fff;
		text-align: left;
		line-height: 30px;
		height: 30px;
		font-size: 14px;
		font-family: '\5FAE\8F6F\96C5\9ED1';
		background: #3498db;
		position: relative;
		cursor: move;
	}
	.box-hd  .btn-closed{
		position: absolute;
		right: 10px;
		top: 0;
		color: #fff;
		text-decoration: none;
	}
	.box-hd .box-inner{
		width: 300px;
		height: 200px;
		background: #fff;
	}

	</style>
</head>
<body>
<div class="box-hd" id="drag-box">
	<h2>这里是标题<a class="btn-closed" href="javascript:;">关闭</a></h2>
	<div class="box-inner">		
	</div>
</div>
<script type="text/javascript">
window.onload=function(){
	var oBox = document.getElementById('drag-box');
	var l = (document.documentElement.clientWidth-oBox.offsetWidth)/2;
	var t = (document.documentElement.clientHeight-oBox.offsetHeight)/2;
	oBox.style.left = l + 'px';
	oBox.style.top = t + 'px';
	drag('drag-box');
};


/*--------------拖曳效果----------------
*原理:标记拖曳状态dragging ,坐标位置X, Y
*/
function drag(name){
	var oBox = document.getElementById(name);
	var disX=0;
	var disY=0;
	oBox.onmousedown=function(ev){
		var oEvent = ev||event;
		disX=oEvent.clientX-oBox.offsetLeft;
		disY=oEvent.clientY-oBox.offsetTop;
		document.onmousemove=function(ev){
			var oEvent = ev||event;
			var l = oEvent.clientX-disX;
			var t = oEvent.clientY-disY;
			if(l<100){
				l=0;	
			}else if(l>document.documentElement.clientWidth-oBox.offsetWidth-100){
				l=document.documentElement.clientWidth-oBox.offsetWidth;
			}
			if(t<100){
				t=0;	
			}else if(t>document.documentElement.clientHeight-oBox.offsetHeight-100){
				t=document.documentElement.clientHeight-oBox.offsetHeight;
			}
			oBox.style.left=l+"px";
			oBox.style.top=t+"px";
		};
		document.onmouseup=function(){
			document.onmousemove=null;
			document.onmouseup=null;
			oBox.releaseCapture&&oBox.releaseCapture();  //释放鼠标捕获
		};
		oBox.setCapture&&oBox.setCapture();  //捕获
		return false;  //防止冒泡
	};
	
};

</script>
</body>
</html>

One Comment

发表评论

电子邮件地址不会被公开。 必填项已用*标注