gpt4 book ai didi

javascript - 每次点击时移动图像 Javascript

转载 作者:行者123 更新时间:2023-11-28 12:16:43 24 4
gpt4 key购买 nike

我想在每次点击时移动图像,但使用此代码仅适用于一次点击。

function moveright() {
console.log("moveright invoked.");
var myImg = document.getElementById("image");
myImg.style.position = "absolute";
var cLeft = myImg.style.left;
if (cLeft == 500) {
console("Maximum reached.");
} else {
myImg.style.left = (cLeft + 50) + "px";
}
}
<img id="image" src="/image/TiYE3.jpg?s=32&g=1" onclick="moveright()" />

最佳答案

  1. 给出初始左侧位置值。您可以添加如下内联样式:style="left: 0px"

  2. 将左侧值解析为整数,然后添加 50 px:var cLeft = parseInt(myImg.style.left);

function moveright() {
var myImg = document.getElementById("image");
myImg.style.position = "absolute";
var cLeft = parseInt(myImg.style.left);

if (cLeft == 500) {
console("Maximum reached.");
} else {
myImg.style.left = (cLeft + 50) + "px";
}
}
<img id="image" src="/image/TiYE3.jpg?s=32&g=1" onclick="moveright()"  style="left: 0px" />

或者,您可以跳过 left 样式声明并使用 window.getCompulatedStyle 获取计算的样式值。

function moveright() {
var myImg = document.getElementById("image");
myImg.style.position = "absolute";

var cLeft = parseInt(window.getComputedStyle(myImg).left);

if (cLeft == 500) {
console("Maximum reached.");
} else {
myImg.style.left = (cLeft + 50) + "px";
}
}
<img id="image" src="/image/TiYE3.jpg?s=32&g=1" onclick="moveright()" />

关于javascript - 每次点击时移动图像 Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47865501/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com