I have a div that is 200px in width, and I want this div to decrease in width by the value of a randomized number in javascript.
Like this:
document.getElementById("myGreenHpBar").style.width-randomized number
How would I write it exactly?
This should work:
var width = document.getElementById("myGreenHpBar").style.width;
var new_width = width - random_number;
document.getElementById("myGreenHpBar").style.width = new_width;
This should work:
var div = document.getElementById("div");
div.style.width = "300px";
function rand(){
var randNum = Math.floor(Math.random() * 40) + 1;
div.style.width = subPx(div.style.width, randNum) + "px";
alert(randNum);
}
// Gets : "200px", "50"; Returns 200 - 50
function subPx(a, b){
return parseInt(a, 10) - b;
}
subPx
300px
(the original width of div element) and a randNum
(suppose 10
) as a
and b
respectively. parseInt
method converts 300px
to the integer 300
in base 10
(the second argument). 300
, we subtract 10
(the b
), and get 290
. 290
. rand
function, the expression becomes: div.style.width = 290 + "px"
"px"
is String, the integer 290
gets coerced to the string "290"
and we get the result as: div.style.width = "290px";
Hope that helps !
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.