How to find out if two text nodes are visually

I want to know if two text nodes are visually sequential, regardless of the HTML structure, that is, that there is no empty line or any other element between them.

I use Ranges to get rectangles (size and position), but there is a gap between the text nodes (the bottom of the first rectangle does not match the top of the second).

I tried to calculate this distance based on line-height and font-size but could not get the same value.

Here is the JsFiddle with my attempt: https://jsfiddle.net/3behsxxq/5/

Is there any way to calculate this distance?

EDIT: In the first case of jsFiddle code, there are four lines ("first text", "block", "second", "text block") that are visually sequential, that is, visually the distance between them is the same, but the number I get has difference 7 (in this first case). If I try to drop this space based on the difference between the line height / font size and the range values, they do not match, so I cannot counteract this.

EDITING 2. Context: in the image below, 6 lines have the same distance between them. I am looking for a way to determine that they are part of the same paragraph, regardless of the html structure (because html can have a <p> element or any other element to represent the paragraph).

enter image description here

+12
javascript css form-control
source share
1 answer
 var extractTextNodes = function(paragraph) { var nodes = []; function callback(node) { if (node.nodeType === Node.TEXT_NODE) { nodes.push(node); } else if (node.nodeType === Node.ELEMENT_NODE) { node.childNodes.forEach(callback); } } paragraph.childNodes.forEach(callback); return nodes; }; var findParentParagraph = function(node) { var parent = node.parentElement; while (parent) { if (parent.tagName === "P") { return parent; } parent = parent.parentElement; } return null; }; var areTextNodesSiblings = function(textNode1, textNode2) { var p = findParentParagraph(textNode1); if (!p) { return false; } var allTextNodes = extractTextNodes(p); var index1 = allTextNodes.indexOf(textNode1); var index2 = allTextNodes.indexOf(textNode2); if (index2 === -1) { return false; } return (index1 === index2 - 1) || (index1 === index2 + 1); }; 

And just call areTextNodesSiblings passing the nodes.

Violin: https://jsfiddle.net/krmnve37/1/


The name reads โ€œvisually consistent,โ€ but โ€œedited 2. contextโ€ says the nodes should be in the same paragraph. The following function will check if two nodes are in the same paragraph, and not whether they are next to each other:

 var areTextNodesInTheSameParagraph = function(textNode1, textNode2) { var p = findParentParagraph(textNode1); if (!p) { return false; } var allTextNodes = extractTextNodes(p); var index1 = allTextNodes.indexOf(textNode1); var index2 = allTextNodes.indexOf(textNode2); return index1 > -1 || index2 > -1; }; 
0
source share

All Articles