I am working on an online reading website, and I want to put the article in an fixed-size div. The article is a string with no line break, but it will be presented in many lines in the div. If I know exactly the font-family and the width of div, do I have any chance of getting the line number of a specific word. (I want to do this because the article have some notes related to it, and I need to make sure the notes appears in the right place.) Do this job on the server or client is all ok.
Asked
Active
Viewed 53 times
-1
-
Maybe? Can you share with us what you have tried? – Jay Blanchard Oct 20 '14 at 13:03
-
http://stackoverflow.com/questions/783899/how-can-i-count-text-lines-inside-an-dom-element-can-i – Robin Oct 20 '14 at 13:06
-
I really don't know how to do, but I think making ebooks which cut books into pages may face the problem, otherwise they even don't know how many pages are there. – GiantWing Oct 20 '14 at 14:06
1 Answers
0
Not sure how accurate this is but it is working with the fiddle: http://jsfiddle.net/pp2jawoz/
var searchWord = 'condimentum';
var searchContainer = $('[data-search="container"]');
searchContainer.html(searchContainer.html().replace(searchWord, '<span class="searched" data-search="word">' + searchWord + '</span>'));
var searchWordContainer = $('[data-search="word"]');
var line = Math.round((searchWordContainer.offset().top - searchContainer.offset().top) / searchWordContainer.height());
console.log(line);
Updated fiddle for fonts and multiple word search: http://jsfiddle.net/pp2jawoz/2/
Note: This script works as long as the line-height is set with the change of font as each font is slightly different, this might also be dependent on OS.

Gavin Hellyer
- 328
- 1
- 9
-
I think We may need to use the font-family information because different font-family use different size to hold a specific character. Some fixed width font like Courier and unfixed font like sans serif will get different answer in this problem. – GiantWing Oct 20 '14 at 14:12
-
I need to know the line number before the articles are put in the DOM, because I want to present the notes which is related to part of the article. Anyway, thanks a lot! – GiantWing Oct 20 '14 at 14:21
-
unless you had the exact size for every character of the fonts, the div and the line-height then this would be impossible to do before dom insertion... – Gavin Hellyer Oct 20 '14 at 14:50