我正在实现图像可拖动指令。我的代码在http://plnkr.co/edit/MXnOu6HM1XmMEzot7dn3上,基本上由基本的可移动指令组成

appModule.directive('movable', function ($document) {
        return {
            restrict: 'A',
            require: 'ngModel',
            link: function postLink(scope, element, attrs) {
                var startX = 0,
                    startY = 0,
                    x = 0,
                    y = 0;

                element.css({
                    position: 'absolute'
                });

                function bindElementMove() {
                    element.bind('mousedown', function (event) {
                        // Prevent default dragging of selected content
                        console.log("binding element to move.");
                        startX = event.screenX - x;
                        startY = event.screenY - y;
                        $document.bind('mousemove', moveDiv);
                        $document.bind('mouseup', mouseup);
                    });
                }

                bindElementMove();

                function moveDiv(event) {
                    console.log('im moving');
                    y = event.screenY - startY;
                    x = event.screenX - startX;
                    element.css({
                        top: y + 'px',
                        left: x + 'px'
                    });
                    scope.$apply(function () {
                        scope.tb.x = element.css("top");
                        scope.tb.y = element.css("left");
                    });
                }

                function mouseup() {
                    console.log("mouse up fired - unbind moveDiv and mouseUp");
                    $document.unbind('mousemove', moveDiv);
                    $document.unbind('mouseup', mouseup);
                }
            }
        }
    });

还有一个图像指令
appModule.directive("imgelement", function ($document) {
    return {
        restrict: 'E',
        template: '<div movable resizable constrain deletable rotatable ng-style="{top:tb.x, left:tb.y, height:tb.height, width:tb.width}"><img ng-src="{{tb.blob_url}}"  ng-style="{height:tb.height, width:tb.width}"/></div>',
        require: 'ngModel',
        replace: true,
        link: function (scope, element, attrs) {
            hello = scope;
        }
    };
});

但是,如在plunkr中看到的那样,当我第一次单击图像并尝试拖动时,它会经历mousemove事件的几次传递,然后卡住,不再移动。随后释放鼠标会奇怪地移动图像。任何想法我在这里做错了吗?

最佳答案

Angular.js文档http://docs.angularjs.org/guide/directive中有一个可拖动指令的工作示例

这是您在该指令中的Plunker的分支:http://plnkr.co/edit/RmzmgubOfF1VdU7HaAtp?p=preview

09-30 16:28
查看更多