拖拽有多種寫法,在這里就看一看angular版的拖拽。
<!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" type="text/javascript" charset="utf-8"></script>
<script src="../js/angular.min.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
// 自定義一個模塊
var app = angular.module("myApp",[]);
// 自定義指令 自定義指令時一定要使用駝峰命名法
app.directive('myDrag',function(){
// 返回一個函數
return{
link : function(scope,element,attr){
// scope可以接收到的數據
// element 當前的元素
// attr屬性
// 拖拽的三大事件mousedown,mousemove,mouseup.使用jq綁定事件的方法進行綁定
element.on('mousedown',function(ev){
// 通過event獲取到當前對象
var This = $(this);
// 獲取到鼠標離當前元素上邊框的距離
var disX = ev.clientX - $(this).offset().left;
// 獲取到元素距離左邊框的距離
// 因為在拖拽的過程中不變的是鼠標距離元素邊框的距離 通過不變和已知求變量
var disY = ev.clientY - $(this).offset().top;
$(document).on('mousemove',function(ev){
// 將所改變的值通過樣式設置給當前元素
This.css({
left:ev.clientX - disX,
top:ev.clientY - disY,
});
});
$(document).on('mouseup',function(){
// 鼠標松開時關閉所有事件
$(document).off();
})
})
},
restrict:'A', //ECMA E元素 C類名 M注釋 A屬性
};
});
</script>
</html>
