繁体   English   中英

Angularjs 指令使 HTML 元素可拖动并且其中的 HTML 字段可选择或可修改

[英]Angularjs Directive to make HTML element draggable and HTML fields within it selectable or modifiable

我尝试了很多东西,但没有一个有效。 因此,发布相同的内容。

这是背景:

我有这个HTML元素,它将基于ng-repeat动态创建一个矩形框。 在每个Rectangular框中都有各种 HTML 元素,例如HTML select and input text等,这些字段可以由用户编辑。 我想让这个矩形框draggable ,以便用户可以移动它。

因此,我编写了一个angularjs directive来完成它并且它工作正常但是如果我添加指令,那么select字段和rectangular框内的所有字段都不再可编辑,因为它将draggable directive应用于整个rectangular 如果我删除此指令,那么它会正常工作。 如何使rectangulardraggable ,以及其中的字段selectable or editable

HTML CODE

<div ng-repeat="NewField in NewFieldValues">
    <div style="width:250px;height:120px;border:1px solid #000;" draggable draggable="true">
        <select ng-model="Dynamic.BusinessStep[NewField.ID]" ng-change="BusinessStepChange(NewField.ID,'BusinessStep')" class="form-control">
            <option class="dropdown-item" value="" selected> Choose Business Step</option>
            <option class="dropdown-item" ng-repeat="businessStep in businessSteps" value="{{ businessStep.value }}"> {{ businessStep.text }} </option>
        </select>
        <br/>
        <input type="text" ng-model="Dynamic.ObjectCount[NewField.ID]" ng-blur="BusinessStepChange(NewField.ID,'EventCount')" placeholder="number of objects" class="form-control"></input>
    </div>
    <br/>
</div>

Angularjs Directive:

app.directive('draggable', function($document) {
    return 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',
            display: 'block'
        });
        
        element.on('mousedown', function(event) {
            console.log("MOUSE DOWN");
            // Prevent default dragging of selected content
            event.preventDefault();
            startX = event.screenX - x;
            startY = event.screenY - y;
            $document.on('mousemove', mousemove);
            $document.on('mouseup', mouseup);
            return true;
        });

        function mousemove(event) {
            console.log("MOUSE MOVE");
            y = event.screenY - startY;
            x = event.screenX - startX;
            element.css({
              top   : y + 'px',
              left  : x + 'px'
            });
            return true;
        }

        function mouseup() {
            $document.off('mousemove', mousemove);
            $document.off('mouseup', mouseup);
            return true;
        }
    };
});

一瞥我正在努力实现的目标

我试图改变一些东西,但它们都不起作用。 当我尝试将draggable对象添加到矩形框中时,默认情况下其中的字段会获取draggable directive ,因此它们的default行为被angularjs directive覆盖。 如果有人可以在这里为我提供一些指导,我将不胜感激。

您面临的问题称为Event-Bubbling 点击事件冒泡到触发拖动事件的容器矩形。

解决方案是简单地实现$event.stopPropagation(); ,这样做是为了防止相关的$event冒泡并触发其他类似事件。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM