[英]jquery draggable, making a div not to go outside of the other div frame
我需要一個可拖動的div不能超出第二個div框架,到目前為止,如果可拖動的div在另一個div的框架內,我設法使“碰撞”基本上返回true或false。 所以現在的問題是,我無法使它正常工作,當它碰到框架和更多示例時,我試圖將其設為ax = 90(example),但我只是無法使其正常工作。 可拖動的div不想回到原位。
這是一個JSFiddle: https://jsfiddle.net/kojaa/x80wL1mj/2/
://jsfiddle.net/kojaa/x80wL1mj/2/
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="style.css">
<title>Catch a ball</title>
</head>
<body>
<div class="catcherMovableArea" id="catcherMovableArea">
<div id="catcher" class="catcher"></div>
</div>
<script src="script.js"></script>
</body>
</html>
.catcherMovableArea {
position: absolute;
border: 1px solid black;
width: 1900px;
top: 90%;
height: 50px;
}
.catcher {
position: absolute;
width: 250px;
height: 30px;
border-radius: 10px;
background-color: black;
top: 20%;
}
let catcher = $("#catcher");
$(document).mousemove(function(e) {
catcher.position({
my: "left-50% bottom+50%",
of: e,
collision: "fit"
});
let catcherOffset = $(catcher).offset();
let CxPos = catcherOffset.left;
let CyPos = catcherOffset.top;
let catcherYInMovableArea, catcherXInMovableArea = true;
while(!isCatcherYinMovableArea(CyPos)){
catcherYInMovableArea = false;
break;
}
while(!isCatcherXinMovableArea(CxPos)){
catcherXInMovableArea = false;
break;
}
});
function isCatcherYinMovableArea(ypos){
if(ypos < 849.5999755859375 || ypos > 870.5999755859375) {
return false;
} else {
return true;
}
}
function isCatcherXinMovableArea(xpos){
if(xpos < 8 || xpos > 1655 ) {
return false;
} else {
return true;
}
}
默認情況下, collision
選項將阻止將元素放置在window之外。 您要防止它移到特定元素之外。
為此,請使用“ within
選項來選擇應將哪個元素用於容納。
例:
let draggable = $("#draggable"); $(document).mousemove(function(e) { draggable.position({ my: "left-50% bottom+50%", of: e, collision: "fit", within: "#container" }); });
#container { width: 200px; height: 100px; border-style: solid } #draggable { width: 50px; height: 50px; background-color: black }
<script src="https://code.jquery.com/jquery-3.3.1.js"></script> <script src="https://code.jquery.com/ui/1.12.0-rc.1/jquery-ui.js"></script> <div id="container"> <div id="draggable"></div> </div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.