JavaScript: drag within the page, drag selected text to solve the problem within the page

Deck: drag the box in the page

Before dragging the entire html document div block, the block is now applied to a parent div div, the div sub-drag parent div as follows:

Only if the judge to modify the width of the visible region in the previous sentence basis.

		document.onmousemove = function(ev){
			var l = ev.clientX - disX;
			var t = ev.clientY - disY;
			if (l<30) {
				l = 0;
			} else if(l>oDiv2.offsetWidth-oDiv1.offsetWidth){
				l = oDiv2.offsetWidth-oDiv1.offsetWidth;
			}//div块不超出左右两边,oDiv2.offsetWidth是div2可视区的宽度
			if (t<30) {
				t = 0;
			} else if(t>oDiv2.offsetHeight-oDiv1.offsetHeight){
				t = oDiv2.offsetHeight-oDiv1.offsetHeight;
			}//div块不超出上下两边,oDiv2.offsetHeight是div2可视区的高度
			
			oDiv1.style.left = l + 'px';
			oDiv1.style.top = t + 'px';
		};

 Complete example:

<!DOCTYPE html>
<html>
<head>
	<title>拖拽</title>
<style type="text/css">
	#div1{ height: 100px; width: 100px; background-color: red; position: absolute; }
	#div2{ height: 600px; width: 800px; background-color: gray; position: relative; }
</style>
<script type="text/javascript">
window.onload = function(){
	document.oncontextmenu = function(){
		return false;
	}
	var oDiv1 = document.getElementById('div1');
	var oDiv2 = document.getElementById('div2');

	var disX = 0;
	var disY = 0;

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

		document.onmousemove = function(ev){
			var l = ev.clientX - disX;
			var t = ev.clientY - disY;
			if (l<30) {
				l = 0;
			} else if(l>oDiv2.offsetWidth-oDiv1.offsetWidth){
				l = oDiv2.offsetWidth-oDiv1.offsetWidth;
			}//div块不超出左右两边,oDiv2.offsetWidth是div2可视区的宽度
			if (t<30) {
				t = 0;
			} else if(t>oDiv2.offsetHeight-oDiv1.offsetHeight){
				t = oDiv2.offsetHeight-oDiv1.offsetHeight;
			}//div块不超出上下两边,oDiv2.offsetHeight是div2可视区的高度
			
			oDiv1.style.left = l + 'px';
			oDiv1.style.top = t + 'px';
		};

		document.onmouseup = function(){
			document.onmousemove = null;
			document.onmouseup = null;
		};
		return false;
	};
};
</script>
</head>
<body>ajsoigjiagioanreihirea
<div id="div2">
	jloajosjog[adgoiaog]
	<div id="div1"></div>
</div>

</body>
</html>

Finally, add a return false statement, you can solve the problem while dragging the selected text within the page.

determining if the following function is to increase the adsorption, when the frame is less than the distance div1 div2 near 30 pixels, the distance directly set to zero.

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

Guess you like

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