html5 drag demo
angular.module('dragModule', [])
.directive('myDraggable', ['$document', function($document) {
return {
link: function(scope, element, attr) {
var startX = 0, startY = 0, x = 0, y = 0;
element.css({
position: 'relative',
border: '1px solid red',
backgroundColor: 'lightgrey',
cursor: 'pointer'
});
element.on('mousedown', function(event) {
// Prevent default dragging of selected content
event.preventDefault();
startX = event.pageX - x;
startY = event.pageY - y;
$document.on('mousemove', mousemove);
$document.on('mouseup', mouseup);
});
function mousemove(event) {
y = event.pageY - startY;
x = event.pageX - startX;
element.css({
top: y + 'px',
left: x + 'px'
});
}
function mouseup() {
$document.off('mousemove', mousemove);
$document.off('mouseup', mouseup);
}
}
};
}]);
效果如上
效果如上
angular
.module('app')
.directive('dragdrop', [function () {
return {
scope: {},
link: (scope, element, attrs) => {
var el = element[0];
el.draggable = true;
el.addEventListener(
'dragstart',
function(e) {
let style = window.getComputedStyle(e.target, null);
e.dataTransfer.setData('text/plain',
(parseInt(style.getPropertyValue('left')) - e.clientX) + ',' + (parseInt(style.getPropertyValue('top')) - e.clientY)
);
// console.log(e.clientX, 'start');
},false
);
document.body.addEventListener('dragover',function(e) {
e.preventDefault();
return false;
},false);
document.body.addEventListener('drop',function(e) {
let offset = e.dataTransfer.getData('text/plain').split(',');
// console.log(e.clientX, 'drop',offset);
el.style.left = (e.clientX + parseInt(offset[0])) + 'px';
el.style.top = (e.clientY + parseInt(offset[1])) + 'px';
e.preventDefault();
return false;
},false);
}
};
}
]);