[英]Move image in every click javascript
我嘗試在每次點擊時移動圖像,但它只移動一次。查看代碼:
<img id="myImg" src="">
<script>
function move() {
var img = document.getElementById("myImg")
img.style.left += "2px";
}
</script>
<button onclick="move()"></button>
有誰知道如何使它工作?
當您獲得left
屬性的值時,它看起來像這樣: 0px
。 這是一個字符串。 所以如果你想計算它,你需要把它解析成一個數字。 在此之前,您可以拆分px
部分以獲取數字。
img { position: absolute; width: 150px; height: 100px; left: 0px; } button { margin-top: 100px; }
<img id = "myImg" src = "https://images.unsplash.com/photo-1474511320723-9a56873867b5?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&w=1000&q=80"> <script> function move(){ var img = document.getElementById("myImg"); img.style.left = +img.style.left.substring(0, img.style.left.length - 2) + 2 + 'px'; } </script> <button onclick = "move()">Move</button>
這條線
img.style.left += "2px";
產生無效的 CSS。 您想每次提取整數,加 2,然后重新添加“px”單位。
const img = document.getElementById("myImg") function move() { img.style.marginLeft = img.style.marginLeft ? parseInt(img.style.marginLeft, 10) + 2 + "px" : "2px" }
<img id="myImg" src="https://placekitten.com/200/200"> <button onclick="move()">Move Image</button>
這是移動圖像的一種非常笨拙的方式。 請自學有關畫布對象的知識。 但是由於您是初學者並且可能只需要快速修復,這里有一種方法可以讓您的代碼正常工作:
<img id = "myImg" style="width: 100px; height: 100px;" src ="https://upload.wikimedia.org/wikipedia/en/thumb/e/ec/Soccer_ball.svg/600px-Soccer_ball.svg.png"> <script> var margin = 0; function move(){ var img = document.getElementById("myImg") margin += 2; img.style.marginLeft = margin + "px"; } </script> <button onclick = "move()" >Move</button>
如果你想移動圖像,那么你可以向右或向左移動它來嘗試在left - px
修復你的代碼left - px
<img id = "myImg" src = "">
<script>
function move(){
var img = document.getElementById("myImg")
img.style.left += "2px";
}
function moveleft() {
imgObj.style.left = parseInt(imgObj.style.left) + 10 + 'px';
}
</script>
<button onclick = "moveleft();">
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.