Home > Web Front-end > JS Tutorial > body text

How to implement drag and drop events in native js (code)

不言
Release: 2018-08-15 17:33:50
Original
1552 people have browsed it

The content of this article is about how to implement drag and drop events (code) in native js. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<style>
		.box{
			width:200px;
			height:200px;
			background-color: red;
			position: absolute;
			left:0;
			top:0;
		}
	</style>
</head>
<body>
	<p class=&#39;box&#39;></p>
	<script>
		var box = document.querySelector(&#39;.box&#39;);
		box.onmousedown = function(e){
			var event = e || window.event;
			var target = event.target || event.srcElement;
			var disX = event.clientX - target.offsetLeft;
			var disY = event.clientY - target.offsetTop;
			document.onmousemove = function(event){
				// 注意:这里要有自己的事件对象
				target.style.left = event.clientX - disX + &#39;px&#39;;
				target.style.top = event.clientY - disY + &#39;px&#39;;
				document.onmouseup = function(){
					document.onmousedown = null;
					document.onmousemove = null;
				}
			}
		}
	</script>
	
</body>
</html>
Copy after login

Related recommendations:

js control file dragging and get the drag content implementation code

js simple table Drag_javascript skills

Native JS to achieve drag and drop image effect_javascript skills

The above is the detailed content of How to implement drag and drop events in native js (code). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template