[英]having problems adding commas to number while limiting it to only 2 decimal places
[英]Problems while adding a number to width attribute
單擊按鈕后,我的代碼應該每 200 毫秒使我的圖像變寬 1px,但我覺得它增加了 20-30。
這是我的代碼<img id="testimage" src="wall.png" width="50" height="25"/>
setInterval( function() {var im = document.getElementById("testimage");
var newWidth = (im.getAttribute("width") ? im.getAttribute("width") : 0) + 1; //here
im.setAttribute("width", newWidth); console.log(im.getAttribute)}, 200)
}
將寬度從字符串轉換為數字以執行加法而不是字符串連接。 這可以使用一元加運算符來完成。
var newWidth = (im.getAttribute("width") ? +im.getAttribute("width") : 0) + 1;
或者,直接更新width
屬性,它是一個數字。
let im = document.getElementById("testimage"); setInterval(function() { ++im.width; }, 200);
<img id="testimage" src="https://via.placeholder.com/50x50" width="50" height="50"/>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.