首页 > 解决方案 > 使用四个按钮在 div 内移动 div

问题描述

对于学校项目,我必须在大矩形内创建一个大矩形和一个小矩形。然后我必须创建四个按钮来移动大矩形(10px)内的小矩形。

我是 JS 的新手,所以我不知道如何开始。

如果有人能给我一个如何开始的建议,那将非常有帮助。

#bigd {
  border: 1px solid black;
}

#move {
  border: 1px solid black;
  position: absolute;
}
<div id="bigd" style="width:1000px; height:600px;">
  <div id="move" style="left:450px; top:260px; width: 40px; height: 40px;"> </div>

</div>
<button type="button" onclick="left()">Links</button>
<button type="button" onclick="right()">Rechts</button>
<button type="button" onclick="up()">Auf</button>
<button type="button" onclick="down()">Ab</button>

标签: javascripthtmlcss

解决方案


这是一个开始。确保您调用选择器的方式与属性中的相同

移动=开始

其余的自己试试。提示:使用 .top

const box = document.getElementById("move");
const step = 10;
// We just use left in both cases
const left = () => {
  let lft = parseInt(box.style.left)
  if (lft >= document.getElementById("bigd").offsetLeft+step) box.style.left = (lft-step)+"px";
};  
const right = () => {
  let lft = parseInt(box.style.left)
  if (lft <= document.getElementById("bigd").width-step) box.style.left = (lft+step)+"px";
};  
#bigd {
  border: 1px solid black;
}

#move {
  border: 1px solid black;
  position: absolute;
}
<div id="bigd" style="width:5000px; height:400px;">
  <div id="move" style="left:450px; top:260px; width: 40px; height: 40px;">Box</div>

</div>
<button type="button" onclick="left()">Links</button>
<button type="button" onclick="right()">Rechts</button>
<button type="button" onclick="up()">Auf</button>
<button type="button" onclick="down()">Ab</button>


推荐阅读