Home > Web Front-end > JS Tutorial > Example code for drag and drop using angular

Example code for drag and drop using angular

零下一度
Release: 2017-07-18 17:40:49
Original
1356 people have browsed it

There are many ways to write drag and drop. Let’s take a look at the angular version of drag and drop. The code is as follows:

<!DOCTYPE html>
<html ng-app="myApp">
	<head>
		<meta charset="UTF-8">
		<title></title>
		<style type="text/css">
			#box{
				width: 100px;
				height: 100px;
				background: black;
				/*一定要给当前元素设置绝对定位*/
				position: absolute;
				left: 0;
				top: 0;
			}
		</style>
	</head>
	<body>
		<div id="box" my-drag></div>
	</body>
		<script src="jquery-3.1.1.min.js?1.1.11" type="text/javascript" charset="utf-8"></script>
		<script src="../js/angular.min.js?1.1.11" type="text/javascript" charset="utf-8"></script>
		<script type="text/javascript">
//			自定义一个模块
			var app = angular.module("myApp",[]);
//			自定义指令  自定义指令时一定要使用驼峰命名法
			app.directive(&#39;myDrag&#39;,function(){
//				返回一个函数
				return{
					link : function(scope,element,attr){
//						scope可以接收到的数据
// 						element 当前的元素
//						attr属性

//						拖拽的三大事件mousedown,mousemove,mouseup.使用jq绑定事件的方法进行绑定
						element.on(&#39;mousedown&#39;,function(ev){
//							通过event获取到当前对象
							var This = $(this);
//							获取到鼠标离当前元素上边框的距离
							var disX = ev.clientX - $(this).offset().left;
//							获取到元素距离左边框的距离  
//							因为在拖拽的过程中不变的是鼠标距离元素边框的距离  通过不变和已知求变量
							var disY = ev.clientY - $(this).offset().top;
							$(document).on(&#39;mousemove&#39;,function(ev){
//								将所改变的值通过样式设置给当前元素
								This.css({
									left:ev.clientX - disX,
									top:ev.clientY - disY,
								});
							});
							$(document).on(&#39;mouseup&#39;,function(){
//								鼠标松开时关闭所有事件
								$(document).off();
							})
						})
					},
					restrict:&#39;A&#39;, //ECMA    	E元素  C类名 M注释 A属性
				};
			});
		</script>
</html>
Copy after login

 

The above is the detailed content of Example code for drag and drop using angular. 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