当css作为绝对位置并且它的父div具有css作为位置相对时,如何使图像可拖动?

时间:2017-01-18 14:12:06

标签: javascript jquery html css jquery-ui

这是我的代码部分:

<div id="canvasImg" class="img-content position-relative">
    <loading></loading>
    <canvas id="Canvas" class="position-absolute"></canvas>
</div>

使用的CSS:

.position-relative{
    position: relative;
}
.position-absolute{
    position: absolute;
}

生成画布图像后,我正在动态创建一些图像。

var createCanvasImgDiv = function (markerDetails) {
            var result = "<img src='../../../../../sharedAssets/images/device_marker.png'"
                    + "class='position-absolute marker-Img'"
                    + "id='" + markerDetails.deviceId + "'"
                    + "name='" + markerDetails.externalName + "'"
                    + "radius='" + markerDetails.radius + "'"
                    + "emailTags='" + markerDetails.emails.join(",") + "'"
                    + "/>";
            return result;
        };
_.map(deviceMarkers, function (tempMarker) {
                var imagDiv = createCanvasImgDiv(tempMarker);
                $("#canvasImg").append(angular.element(imagDiv));
                $compile(angular.element(imagDiv))($scope);
            });

现在我希望<img>对象在拖动鼠标时移动到父div(id = canvasImg)内的任何位置。我想要鼠标位置下降时的位置。

请帮我解决这个问题。提前谢谢。

1 个答案:

答案 0 :(得分:1)

我已使用jquery-ui draggable widget来实现此目标。

&#13;
&#13;
$("#image").draggable({
  containment: "parent"
});
$("#image").on("dragstop", function(event, ui) {
  alert("mouse position: X:" + event.pageX + ", Y:" + event.pageY);
});
&#13;
.position-relative {
  position: relative;
}
.position-absolute {
  position: absolute;
}
&#13;
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<div id="canvasImg" class="img-content position-relative" style="width:300px;height:200px;border:1px solid #000000;">
  <loading></loading>
  <canvas id="Canvas" class="position-absolute" style="width:200px;height:100px;border:1px solid #000000;"></canvas>
  <img id="image" class="position-relative" src="http://wallpaper.sc/en/ipad/wp-content/uploads/2014/10/ipad-2048x2048-thumbnail_00721-256x256.jpg" style="width:25px;height:25px;" />
</div>
&#13;
&#13;
&#13;