我試圖製作一個帶有兩個框的Web應用程序,一個包含在另一箇中。用戶應該能夠點擊並移動內框,但是用戶不應該能夠將該框移動到外框的範圍之外。用戶可以通過將內盒拖動到外盒的一個邊緣來移動外盒。我知道如何移動內部盒子,但問題是如何移動另一個盒子的限制。有人可以幫我嗎?這是我到目前爲止所做的:如何在javascript中移動一個div與另一個div
<!doctype html>
<head>
<title>JavaScript Game</title>
<style>
#container {
height:400px;
width:600px;
outline: 1px solid black;
position:absolute;
left:50px;
top: 0px;
background-color:green;
}
#guy {
position:absolute;
height:50px;
width:50px;
outline: 1px solid black;
background-color:red;
left: 200px;
top: 200px;
}
</style>
</head>
<body>
<div id="container"></div>
<div id="guy"></div>
<script>
var guy=document.getElementById("guy");
var cont=document.getElementById("container");
var lastX,lastY; // Tracks the last observed mouse X and Y position
guy.addEventListener("mousedown", function(event) {
if (event.which == 1) {
lastX = event.pageX;
lastY = event.pageY;
addEventListener("mousemove", moved);
event.preventDefault(); // Prevent selection
}
});
function buttonPressed(event) {
if (event.buttons == null)
return event.which != 0;
else
return event.buttons != 0;
}
function moved(event) {
if (!buttonPressed(event)) {
removeEventListener("mousemove", moved);
} else {
var distX = event.pageX - lastX;
var distY = event.pageY - lastY;
guy.style.left =guy.offsetLeft + distX + "px";
guy.style.top = guy.offsetTop + distY + "px";
lastX = event.pageX;
lastY = event.pageY;
}
}
</script>
</body>
謝謝,但你的「if」聲明效果不好,我已經嘗試了很多if語句,至今沒有運氣 –
已修復,如果我明白你想要這個作品。在片段中放一下。 – Icewine
@Icewine解決方案也適用於我,可能是您的瀏覽器。 –