javascript - JavaScript 按 X px 按钮移动对象
问题描述
我应该如何通过按钮将对象移动(在这种情况下)10px?在我的代码中,左右按钮不起作用,向上和向左移动图像,但不是 10px,到顶部/左侧边缘。我试过这个:
解决方案
首先是您的图片没有定位,这意味着它static
默认定位,因此您不能使用左、右、上或下样式属性。我已将父母的定位设置为relative
和孩子的(img)位置,absolute
以便图像的定位将相对于父母(在您的情况下为身体)。
我认为您还想在每次单击按钮时进行增量分配,在这种情况下,您应该首先获取图像的当前位置。您可以使用offsetTop
和offsetLeft
属性来做到这一点。
body {
position: relative;
}
img {
position: absolute;
left: 200px;
top: 100px;
}
<body>
<img onclick="A()" id='inspo' src="a8.jpg">
<button id="left" onclick="moveleft()">left</button>
<button class="right" onclick="moveright()">right</button>
<button class="down" onclick="movedown()">down</button>
<button class="up" onclick="moveup()">up</button>
<script type="text/javascript">
function moveleft() {
const img = document.getElementById('inspo');
img.style.left = `${img.offsetLeft - 10}px`;
}
function moveright() {
const img = document.getElementById('inspo');
img.style.left = `${img.offsetLeft + 10}px`;
}
function moveup() {
const img = document.getElementById('inspo');
img.style.top = `${img.offsetTop - 10}px`;
}
function movedown() {
const img = document.getElementById('inspo');
img.style.top = `${img.offsetTop + 10}px`;
}
function A() {
document.getElementById('inspo').style.display = "none";
}
</script>
</body>
编辑:如果你想保持你的原始样式和使用left
和top
属性不仅设置值而且获取值,你可以使用下面的代码,注意left
和top
属性返回字符串,所以你必须在进行算术之前将结果转换为数字对其进行操作。
<body style="position: relative;">
<img style=" position: absolute; left: 100px; top: 100px;" onclick="A()" id='inspo' src="a8.jpg">
<button id="left" onclick="moveleft()">left</button>
<button class="right" onclick="moveright()">right</button>
<button class="down" onclick="movedown()">down</button>
<button class="up" onclick="moveup()">up</button>
<script type="text/javascript">
function moveleft() {
const img = document.getElementById('inspo');
img.style.left = Number(img.style.left.slice(0, -2)) - 10 + 'px';
}
function moveright() {
const img = document.getElementById('inspo');
img.style.left = Number(img.style.left.slice(0, -2)) + 10 + 'px';
}
function moveup() {
const img = document.getElementById('inspo');
img.style.top = Number(img.style.top.slice(0, -2)) - 10 + 'px';
}
function movedown() {
const img = document.getElementById('inspo');
img.style.top = Number(img.style.top.slice(0, -2)) + 10 + 'px';
}
function A() {
document.getElementById('inspo').style.display = "none";
}
</script>
</body>
推荐阅读
- python - 如何根据日期解析数据帧
- unix - 如何在 solaris 上制作可加载的内核模块?没有Linux
- vue.js - Vue js如何将一个方法(vuex mapGetters方法)全局导入到项目中
- scala - 使用具有常量值的 var 在 Spark DataFrame 中创建新列
- python - 如何使用 Python 将多个大型 .csv 文件导入并读取到 SQL 数据库中的表中?
- r - R的sum()函数中的条件语句
- vue.js - Pusher ChatKit - 房间和房间订阅 - 如何检测新消息
- javascript - 如何将 JSON 文件从 Android 上传到 Firebase 存储?
- asp.net - ASP.NET 2.0 win10无法编译调试?
- javascript - 单击时加载 HMTL5 音频(不是之前,以提高页面速度)