7

目标是在这里找到最宽单词的宽度。

文本是由不同字体的单词组成的句子,如图所示。

字体范围 html看起来像:

<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> 

所以,这里的第三个词是最宽的。有任何想法吗?一切都是 html,我们可以使用任何东西(jquery、ES5 技术等)。

4

3 回答 3

1

我认为这假装是一个解决方案。

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

于 2012-09-19T19:20:11.420 回答
0

尝试下面的解决方案,它基本上遍历所有跨度并找到最长的单词。

$(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);
});

演示:http: //jsfiddle.net/WtcEQ/32/

于 2012-09-19T20:29:31.763 回答
0

可以max-content用来测量文本的像素宽度。

function measureLongestWordPxWidth(template) {
  const measurer = template.cloneNode(true);
  measurer.style.setProperty("position", "position", "important");
  measurer.style.setProperty("visibility", "hidden", "important");
  measurer.style.setProperty("width", "max-content", "important");

  document.body.appendChild(measurer);
  const { width } = measurer.getBoundingClientRect();
  document.body.removeChild(measurer);
  return width;
}

const spans = [...document.querySelectorAll('span')];
const widths = spans.map(measureTextPxWidth);
const maxWidth = Math.max(...widths);
const maxWidthIndex = widths.indexOf(maxWidth)
const maxWidthText = spans[maxWidthIndex].innerText
  
document.querySelector('.output').innerText = 
  `"${maxWidthText}": ${maxWidth}px`
<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> 

<div class="output"></div>

于 2021-12-01T03:01:33.463 回答