JavaScript: framed drag

Deck: drag the box inside JavaScript- page

Entrain the box, you drag the red div, div to not move, but the emergence of a dashed box, move to the dotted box where, after releasing the mouse to move to where div. Results are as follows:

The general idea: When the mouse is pressed, create a dashed box box. When the mouse is moved, it will be assigned to coordinate the dashed box. When the mouse will relax the dotted rectangle coordinates assigned to the div, then delete the dashed box. Sample code is as follows.

<!DOCTYPE html>
<html>
<head>
	<title>拖拽</title>
<style type="text/css">
	#div1{ height: 200px; width: 200px; background-color: red; position: absolute; }
	.box{ border:1px dashed black; position: absolute;}
</style>
<script type="text/javascript">
window.onload = function(){
	document.oncontextmenu = function(){
		return false;
	}
	var oDiv1 = document.getElementById('div1');

	var disX = 0;
	var disY = 0;

	oDiv1.onmousedown = function(ev){
		disX = ev.clientX - oDiv1.offsetLeft;
		disY = ev.clientY - oDiv1.offsetTop;

		var oBox = document.createElement('div');
		oBox.className = 'box';
		oBox.style.width = oDiv1.offsetWidth+'px';
		oBox.style.height = oDiv1.offsetHeight+'px';
		oBox.style.left = oDiv1.offsetLeft+'px';
		oBox.style.top = oDiv1.offsetTop+'px';
		document.body.appendChild(oBox);
		//当鼠标按下时,创建一个虚线框box,创建的虚线框的位置和div的位置一致。


		document.onmousemove = function(ev){
			var l = ev.clientX - disX;
			var t = ev.clientY - disY;
			if (l<30) {
				l = 0;
			} else if(l>document.documentElement.clientWidth-oDiv1.offsetWidth){
				l = document.documentElement.clientWidth-oDiv1.offsetWidth;
			}
			if (t<30) {
				t = 0;
			} else if(t>document.documentElement.clientHeight-oDiv1.offsetHeight){
				t = document.documentElement.clientHeight-oDiv1.offsetHeight;
			}
			
			oBox.style.left = l + 'px';
			oBox.style.top = t + 'px';
			//鼠标移动时,将坐标赋值给虚线框。
		};

		document.onmouseup = function(){
			document.onmousemove = null;
			document.onmouseup = null;

			oDiv1.style.left = oBox.offsetLeft+'px';
			oDiv1.style.top = oBox.offsetTop+'px';
			document.body.removeChild(oBox);
			//鼠标方放开时,将虚线框的坐标赋值给div,随即删除掉虚线框。
		};
		return false;
	};
};
</script>
</head>
<body>
	<div id="div1"></div>
</body>
</html>

 

Published 126 original articles · won praise 7 · views 10000 +

Guess you like

Origin blog.csdn.net/qq_36880027/article/details/104514291