简体   繁体   中英

How do I add or subtract the width of an element in JavaScript

I have a bar of which one half is red and other is green. I want it to subtract 1vw from the red element.

style.width deos not work.

Here is my code:


//FIGHT
document.addEventListener("keydown", battle)
function battle(event){
   console.log(event.code)
   document.getElementById("ClickRed").style.width -= "1vw"

   }
      

You can use offsetWidth and offsetHeight to get the total width and height that an element is taking up on the DOM. You can read more about Here

To solve your particular usecase, i personally think that it would be better if you worked with pixels and not viewport width and height because offsetWidth and offsetHeight will return the width and height in pixels instead of vw and vh .

If you have your width and height in pixels, you can use it like this:-

rb.style.width = `${rb.offsetWidth - 100}px`

Try this:

document.getElementById("ClickRed").style.width=(parseFloat(document.getElementById("ClickRed").style.width) - 1) + "vw";

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