Find the width of the widest word in the html block

The goal is to find the width of the widest word here.

The text is a sentence consisting of words with different fonts, as shown in the image.

font ranges html looks like this:

<span style="font:bold 14px Verdana;">LONGESTW</span> <span style="font:bold 42px Verdana;">ORD</span> <span style="font:bold 14px Verdana;">&nbsp;</span> <span style="font:bold 24px Verdana;">ORD</span> <span style="font:bold 14px Verdana;">&nbsp;</span> <span style="font:bold 24px Verdana;">regular</span> <span style="font:bold 14px Verdana;">&nbsp;</span> <span style="font:bold 32px Verdana;">w</span> <span style="font:bold 96px Verdana;">id</span> <span style="font:bold 64px Verdana;">est</span> 

So here the 3rd word is the broadest. Any ideas? All this is html, and we can use any thing (jquery, ES5 methods, etc.).

+6
source share
2 answers

I think this claims to be a solution.

http://jsfiddle.net/WtcEQ/4/

+1
source

Try the solution below, which basically iterates over the entire range and finds the longest word.

 $(function () { var max = 0, sum = 0, lword = '', mword = ''; var $span = $('span'); $.each($span, function (idx, el) { var elTxt = $(el).text().trim(); if (elTxt) { sum += $(this).width(); lword += $(this).text(); } if (!elTxt || $span.length == (idx+1) ) { if (sum > max) { max = sum; mword = lword; } sum = 0; lword = ''; } }); alert(mword + ' ' + max); }); 

DEMO: http://jsfiddle.net/WtcEQ/32/

0
source

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


All Articles