每个列表项中_text_的宽度

时间:2016-10-14 11:48:38

标签: javascript jquery

最好的方法吗? 我试过了:

var listWidth = [];
$('ul li').each(function() {
    listWidth.push($(this).width());
});

虚拟代码:

    <ul>
    <li>Item 1</li>
    <li>Longer item 
    <li>Even longer item</li>
    </ul>

的CSS:

ul {
  width: some fixed width;
}

但它只返回相同的宽度,这也是实际列表项的宽度,而不是文本。

编辑:我想要文本的宽度(以像素为单位)。不是列表本身宽度的字符数

5 个答案:

答案 0 :(得分:1)

将文本换行<span> s并获取其宽度。 <li>标记是块,会扩展到<ul>的宽度,而<span>标记是内联的,只占用所需的宽度(在这种情况下,包围字符)。

var listWidth = [];
$('ul > li > span').each(function() {
    listWidth.push($(this).width());
});

document.write(listWidth);
ul {
  width: 400px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<ul>
    <li><span>Item 1</span></li>
    <li><span>Longer item </span></li>
    <li><span>Even longer item</span></li>
</ul>

答案 1 :(得分:1)

我建议的一种方法如下:

(function($) {

  // creating a named function on the jQuery prototype,
  // which becomes a (very simple, in this case)
  // jQuery plugin
  $.fn.retrieveTextWidth = function() {

    // creating a <span> element into which the
    // content of the passed-in elements, the
    // collection to which the plugin is chained
    // will be temporarily inserted:
    var span = document.createElement('span'),

    // 'empty' variables for later use:
      tmp,
      clone;

    // creating a map of values based on
    // the passed-in collection (the
    // 'this'):
    var res = this.map(function() {

      // cloning the created <span>
      // element:
      clone = span.cloneNode();

      // inserting the cloned <span> ahead of the
      // first child of the current node (from the
      //  jQuery collection, here 'this' refers to
      //  a single Node):
      this.insertBefore(clone, this.firstChild);

      // while the inserted clone has a nextSibling
      // we move that nextSibling into the clone:
      while (clone.nextSibling) {
        clone.appendChild(clone.nextSibling);
      }

      // here we assign the width of the cloned
      // <span> element to a variable:
      tmp = clone.getBoundingClientRect().width;

      // then, while the clone has a firstChild
      // we remove that firstChild and insert it
      // before the clone:
      while (clone.firstChild) {
        clone.parentNode.insertBefore(clone.firstChild, clone);
      }

      // once the clone is empty (after the above
      // while loop has finished) we remove it from
      // the parentNode, removing it from the DOM:
      clone.parentNode.removeChild(clone);

      // once the temporary cloned element has been
      // removed (and the 'tidying up' completed),
      // we return the retrieved clientWidth via
      // the temporary variable:
      return tmp;

    // converting the jQuery map into an
    // Array, consisting only of the found
    // widths:
    }).get();

    // return the Array of widths to the calling
    // context:
    return res;

  };
})(jQuery);

console.log($('ul li').retrieveTextWidth());

&#13;
&#13;
(function($) {
  $.fn.retrieveTextWidth = function() {
    var span = document.createElement('span'),
      tmp,
      clone;

    var res = this.map(function() {
      clone = span.cloneNode();

      this.insertBefore(clone, this.firstChild);

      while (clone.nextSibling) {
        clone.appendChild(clone.nextSibling);
      }

      tmp = clone.getBoundingClientRect().width;

      while (clone.firstChild) {
        clone.parentNode.insertBefore(clone.firstChild, clone);
      }
      clone.parentNode.removeChild(clone);
      return tmp;

    }).get();

    return res;

  };
})(jQuery);

console.log($('ul li').retrieveTextWidth());
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li>one</li>
  <li>A string of arbitrary text</li>
  <li>3</li>
  <li>Lorem ipsum dolor sit amet...okay, I got bored. But, clearly, this is the longest textual content.</li>
</ul>
&#13;
&#13;
&#13;

JS Fiddle demo

参考文献:

答案 2 :(得分:0)

你的意思是text / html的字符长度吗?

var listWidth = [];
$('ul li').each(function() {
    listWidth.push($(this).text().length);
});

不完全确定您要查找的内容,因为相同的liul中的所有ol的宽度都相同,除非您有&#39}另有规定。

修改

每种字体中字符的大小由大写字母M的宽度来衡量。原则上,您可以将字体大小与文本长度相乘,但并非所有字母/字符都与M一样宽。所以你肯定会结束了一大堆......

答案 3 :(得分:0)

如果您使用此CSS,li元素将具有其文本内容的宽度,那么您的JS应该可以工作:

ul {  
  overflow: hidden; 
}
li { 
  float: left;
  clear: left;
}

这是在一个codepen:http://codepen.io/anon/pen/KgBvJW(用背景颜色可见)

答案 4 :(得分:0)

您可以使用Set-Cookie3: OV3176019645=3inkmpee0r5gpfm41c3iltvda1; path="/"; domain=10.11.5.2; path_spec; discard; version=0 measureText()来计算宽度。

canvas

function getWidth(text, font) { var canvas = document.createElement("canvas"); var ctx = canvas.getContext("2d"); ctx.font = font; // important for accurate metrics var metrics = ctx.measureText(text); // TextMetrics object return Math.ceil(metrics.width); } var listWidth = []; $('ul li').each(function() { // put your own font for accurate metrics. listWidth.push(getWidth($(this).text(), 'normal 14pt Arial')); }); 现在将包含每个元素的计算宽度。 如果要将宽度应用于每个listWidth元素,可以使用此代码:

li

这可能有点矫枉过正,但这完全取决于你需要宽度的原因。可能还有其他解决方案可以解决您尝试更有效地实现的目标。