原生js如何实现拖拽事件(代码)

js教程评论633 views阅读模式

本篇文章给大家带来的内容是关于原生js如何实现拖拽事件(代码),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。

<!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='box'></p>
	<script>
		var box = document.querySelector('.box');
		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 + 'px';
				target.style.top = event.clientY - disY + 'px';
				document.onmouseup = function(){
					document.onmousedown = null;
					document.onmousemove = null;
				}
			}
		}
	</script>
	
</body>
</html>

相关推荐:

js控制文件拖拽并获取拖拽内容实现代码

js简单的表拖拽_javascript技巧

原生JS实现拖拽图片效果_javascript技巧

以上就是原生js如何实现拖拽事件(代码)的详细内容,更多请关注php教程其它相关文章!

企鹅博客
  • 本文由 发表于 2020年9月26日 11:47:44
  • 转载请务必保留本文链接:https://www.qieseo.com/405973.html

发表评论