简体   繁体   English

如何在 JavaScript 中添加或减去元素的宽度

[英]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.我希望它从红色元素中减去 1vw。

style.width deos not work. style.width deos 不起作用。

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.您可以使用offsetWidthoffsetHeight来获取元素在 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 .为了解决您的特定用例,我个人认为如果您使用像素而不是视口宽度和高度会更好,因为offsetWidthoffsetHeight将以像素而不是vwvh返回宽度和高度。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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