简体   繁体   English

使用Javascript计算不四舍五入的文本宽度

[英]Calculate text width without rounding using Javascript

I have a div that I using Javascript to change the position of.我有一个 div,我使用 Javascript 来改变它的位置。 However, it is rounding incorrectly.但是,它四舍五入不正确。

 #hi{ background-color: blue; width: 2px; height: 10px; position: absolute; }
 <div id = "hi"></div> <button onclick="myFunction()" style = "margin-top: 100px">Click me</button> <script> function myFunction() { var div = document.getElementById("hi"); div.style.left = "0px"; console.log("BEFORE: " + div.style.left); var moveBy = 109.8125; div.style.left = moveBy + 'px'; console.log("MOVE BY: " + moveBy); console.log("NEW POSITION: " + div.style.left); } </script>

It should move it by 109.8125, but instead moves it by 109.813.它应该将其移动 109.8125,而是将其移动 109.813。

Any way to make it more accurate and move it to 109.8125?有什么方法可以使它更准确并将其移动到 109.8125?

It may seem like it is not that important, but I am doing this several times, so then it looks in the wrong place, relative to other elements.看起来它并不那么重要,但我这样做了好几次,所以相对于其他元素,它看起来是错误的。

If you really need to prevent precision drift due to rounding error, I'd suggest you keep track of the value independently of the style attribute.如果您真的需要防止由于舍入误差导致的精度漂移,我建议您独立于style属性跟踪值。 Here's an example of how you could do it using a data attribute :这是一个如何使用数据属性执行此操作的示例:

 function myFunction() { var div = document.getElementById("hi"); div.style.left = "0px"; console.log("BEFORE: " + div.style.left); var moveBy = 109.8125; // track the current value as a data attribute, // which won't get rounded const left = div.dataset.left = parseFloat(div.dataset.left || 0) + moveBy; // apply the computed value as a style div.style.left = left + 'px'; console.clear(); console.log(`dataset.left: ${left}, style.left: ${div.style.left}`); }
 #hi { background-color: blue; width: 2px; height: 10px; position: absolute; }
 <div id="hi"></div> <button onclick="myFunction()" style="margin-top: 100px">Click me</button>

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

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