javascript - 使用四个按钮在 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>
解决方案
这是一个开始。确保您调用选择器的方式与属性中的相同
移动=开始
其余的自己试试。提示:使用 .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>
推荐阅读
- android - 安卓工作室中的亚行
- nginx - 基于 http_cookie 偏好的国家代码重写到 Nginx 上的相应站点
- python - 默认情况下,如何查看 Series 和/或 DataFrame 中的所有行?
- python - 如何使用元组列表对压缩字典进行排序?
- python - 为什么我的代码适合 Java,但不适合 Python
- java - 从 lambda 表达式中检索值(尝试进行多项选择测验 java fx)
- docker - Kubernetes 在拉取或应用部署时是否支持替代存储库?
- c# - 使用 asp.net 创建 3D 柱形图 - 如何添加 z 轴?
- java - 如何在 Eclipse 中构建一个没有 maven 和 gradle 文件且 repo 中没有 .jar 文件的 Java Github 项目
- javascript - 带有函数()的Javascript随机数生成器