用JavaScript将给定值除以.style.width

我需要在Javascript中划分.style.width函数给定的值。 我的代码如下所示:

    var x = document.getElementsByClassName("item");
    var i;

    var v = x[0].style.width; 

In variable 'v' I have some value in pixels, e.g. 200px width. I would need to divide this value by 2 to get 100px. But this formula doesn't work: var v = x[0].style.width / 2;

我究竟做错了什么?感谢帮助。

评论
放弃幸福
放弃幸福

width will be string. Convert it to number before dividing. This example uses getComputedStyle to get actual width of a dom element

let elem = document.getElementById('test');
let compStyles = window.getComputedStyle(elem);
const widthInteger = parseInt(compStyles.width, 10);
const halfWidth = widthInteger / 2;
console.log(halfWidth)
.test {
  height: 200px;
  width: 200px;
  border: 1px solid green;
}
<div class='test' id='test'></div>
点赞
评论