简体   繁体   中英

How to subtract width of a div with a randomized number in javascript?

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;
}

DEMO

Explanation for subPx

  1. At first button click, it receives 300px (the original width of div element) and a randNum (suppose 10 ) as a and b respectively.
  2. parseInt method converts 300px to the integer 300 in base 10 (the second argument).
  3. From 300 , we subtract 10 (the b ), and get 290 .
  4. Return 290 .
  5. Now in the rand function, the expression becomes: div.style.width = 290 + "px"
  6. Since, "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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM