简体   繁体   English

Javascript 中的给定值除以.style.width

[英]Divide given value by .style.width in Javascript

I would need to divide a value given by.style.width function in Javascript.我需要将由.style.width function 给定的值除以 Javascript。 My code looks like this:我的代码如下所示:

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

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

In variable 'v' I have some value in pixels, eg 200px width.在变量“v”中,我有一些像素值,例如 200px 宽度。 I would need to divide this value by 2 to get 100px.我需要将此值除以 2 才能得到 100px。 But this formula doesn't work: var v = x[0].style.width / 2;但是这个公式不起作用: var v = x[0].style.width / 2;

What am I doing wrong?我究竟做错了什么? Thanks for help.感谢帮助。

width will be string. width将是字符串。 Convert it to number before dividing.在划分之前将其转换为数字。 This example uses getComputedStyle to get actual width of a dom element此示例使用getComputedStyle获取 dom 元素的实际宽度

 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>

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

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