Find the width of an auto-sized item

Basically, I need a span width. Make to use several custom characters that are not found on the keyboard. I create my own input field using the "div". Each character is wrapped with a span tag in which an event listener is connected. This allows the user to click anywhere in the line and move the cursor to the position after the character, and also allows you to add or remove characters in the middle of the line.

I use "offsetLeft" and "offsetWidth" to find the right side of the character, the problem is that when the character / range is clicked, "offsetWidth" is turned off. So, for example, if I use a 14-pixel font, then "M" will return as 35 pixels wide, if in fact it is 11 pixels. And there are several options: the average size, such as "S", will return at 26 pixels when it is actually 9. Thus, there is a difference in size. Now you may wonder how I found the actual size of the letter and used Firebug. Which, if Firebug can find it, I would suggest that I can, I just did not understand how to do this. So I hope someone here knows.

I also tried using "getComputedStyle" and "currentStyle" to find the width, and it returns "auto". Also tried getBoundingClientRect (). width is the same as offsetWidth, and the difference is that it also finds fractions of a pixel in width, so the "M" is 35.366668701171875 pixels wide, odd.

EDIT:

Based on user post 1289347, I should have noticed that "offsetWidth" also causes "offsetLeft" to also turn off with an erroneous amount.

+4
source share
1 answer

Try jquery width (), it calculates dom width very well every time I used it. http://api.jquery.com/width/

And if jquery is out of the question

Create a div in style with the following styles. In your JavaScript, specify the font size and attributes that you are trying to measure, put your string in a DIV, then read the current width and height of the DIV. It will stretch to fit the content, and the size will be within a few pixels of the size of the line.

HTML:

<div id="Test"> abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ</div> 

CSS

  #Test { position: absolute; visibility: hidden; height: auto; width: auto; } 

JavaScript (snippet):

 var test = document.getElementById("Test"); test.style.fontSize = fontSize; var height = (test.clientHeight + 1) + "px"; var width = (test.clientWidth + 1) + "px"; 

This will create a separate test div with your test, credit here. Calculate the width of the text using JavaScript . A lot of work, but it should improve your results by working outside of your existing markup.

-1
source

Source: https://habr.com/ru/post/1403371/


All Articles