我有一些代码可以说明这个问题。
我有一个可以拖动的元素,效果很好。我添加了一个允许用户“放大”的按钮。这就是出错的时候。
问题是,单击缩放按钮后,
containment
的draggable
部分不再遵守父级的左/上/宽和高约束。它仍然受到限制,但受到意想不到的边界位置的限制。
<body style="padding:50px">
<button id="btn">Zoom in</button>
<div id="wrapper" style="background-color:aliceblue;padding:50px;">
<div id="innerWrapper" style="background-color: ivory; min-height: 200px; width: 400px; ">
<div id="draggable" style="background-color:burlywood;max-width:100px;">Move me</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.7.1.min.js" integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo=" crossorigin="anonymous"></script>
<script src="https://code.jquery.com/ui/1.13.2/jquery-ui.min.js" integrity="sha256-lSjKY0/srUM9BE3dPm+c4fBo1dky2v27Gdjm2uoZaL0=" crossorigin="anonymous"></script>
<script>
$("#draggable").draggable({containment:"#innerWrapper"});
const btn = document.getElementById("btn");
btn.addEventListener("click", zoom);
function zoom() {
document.getElementById("innerWrapper").style.transform = "scale(1.2,1.2)";
}
</script>
</body>
事实上,每次单击提供的缩放按钮时,它都会更改包含边界。
我尝试在可拖动对象中添加
drag
事件回调,但仍然无法看到如何解决此问题
发生这种情况是因为
scale()
,它在某些组合中表现得很奇怪,其中之一是当您在容器内有一个可拖动元素时,并且该容器是 scaled
,因此内部元素不会更新实际的它的大小,即使您 destroy
或 disable
和 enable
可拖动元素。
所以你可以自己计算一下包容尺寸:
const draggableElement = $("#draggable")
let containmentArea = $("#innerWrapper");
let percent = 1
draggableElement.draggable({
cursor: "move",
drag: dragFix,
});
function dragFix(event, ui) {
var contWidth = containmentArea.width(),
contHeight = containmentArea.height();
ui.position.left = Math.max(0, Math.min(ui.position.left / percent, contWidth - ui.helper.width()));
ui.position.top = Math.max(0, Math.min(ui.position.top / percent, contHeight - ui.helper.height()));
}
function setScale(scalePercentage) {
percent = scalePercentage;
$("#innerWrapper").css({
'transform': 'scale(' + percent + ')',
'-moz-transform': 'scale(' + percent + ')',
'-webkit-transform': 'scale(' + percent + ')',
'-ms-transform': 'scale(' + percent + ')'
})
}
const btn = document.getElementById("btn");
btn.addEventListener("click", function() {
setScale(1.2)
});
#wrapper {
width: 100%;
height: 300px;
overflow: auto;
background-color: black;
}
#innerWrapper {
background-color: grey;
width: 250px;
height: 250px;
position: relative;
-webkit-transform-origin: 0 0;
-moz-transform-origin: 0 0;
transform-origin: 0 0;
-ms-transform-origin: 0 0;
}
.draggable {
background-color: red;
display: inline;
position: absolute;
top: 10px;
left: 10px;
}
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<button id="btn">Zoom in</button>
<div id="wrapper" style="background-color:aliceblue;padding:50px;">
<div id="innerWrapper" style="background-color: ivory; min-height: 200px; width: 400px; ">
<div id="draggable" style="background-color:burlywood;max-width:100px;">Move me</div>
</div>
</div>