How to calculate text height without changing DOM

I use Range to control the selected text. I would like to calculate the height with which someone began to choose the text where they finished.

I tried the range to the beginning and end of the selected range, and I can accurately calculate the shape of the height, but it changes the DOM and does not allow me to do some other range manipulations, for example, highlighting previously selected text.

I also tried to collect the position of the mosedown and mosueup positions, but I need the exact height from the top of the text selected at the bottom of the text where the selection was released, and this is not always the case.

So, I was wondering if there is a way to calculate the height of the text without changing the DOM?

+6
source share
3 answers

It depends on which browsers you need to solve. Here is a function that will work in IE> = 4 and browsers that support getClientRects() in Range (Firefox> = 4, WebKit since 2009, Opera). If you need support for earlier browsers, you will need to change the DOM, which is really great if you return the DOM to its previous state.

jsFiddle: http://jsfiddle.net/W84yW/

the code:

 function getSelectionHeight() { var selHeight = 0; if (document.selection && document.selection.type == "Text") { var textRange = document.selection.createRange(); selHeight = textRange.boundingHeight; } else if (window.getSelection) { var sel = window.getSelection(); if (sel.rangeCount > 0) { var range = sel.getRangeAt(0); if (!range.collapsed && range.getClientRects) { var startRange = range.cloneRange(); startRange.collapse(true); var selTop = startRange.getClientRects()[0].top; startRange.detach(); var endRange = range.cloneRange(); endRange.collapse(false); selHeight = endRange.getClientRects()[0].bottom - selTop; endRange.detach(); } } } return selHeight; } 
+6
source

I would get the selected text and put it in a hidden div with the same width and the same styles and get its height.

0
source

I do not think the hidden DIV approach will work. Many browsers will either not have a height or will have a height = 0 for hidden elements.

Perhaps if you cloned this part of the DOM and added it to the document with some crazy position (e.g. left: -1000px), you could get the value.

Regardless of the fact that you are having trouble getting consistent results using workarounds, if the Range object doesn't provide this data for you.

0
source

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


All Articles