Javascript:如何计算 DOM 元素内文本元素的行数,例如<li>



我的问题是,javascript中是否有一种方法可以计算元素的行数,例如:

<li classname="link-link"> Lorem Ipsum has been the industry's standard dummy text ever
since the 1500s, when an unknown </li>

未设置行长。此示例可以是 2、3 或 4 行。有类似的问题,但没有一个给出我正在寻找的答案。

您可以获得高度和行高,然后将其四舍五入以获得答案。

.HTML:

<li id="link-link"> Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown </li>

JS (Jquery):

var height = $("#link-link").height()
var fontSize = $("#link-link").css('font-size');
var lineHeight = Math.floor(parseInt(fontSize.replace('px','')) * 1.5);
console.log(Math.ceil(height / lineHeight));

纯JS:

var el = document.getElementById('link-link');
var style = window.getComputedStyle(el, null).getPropertyValue('font-size');
var fontSize = parseFloat(style); 
var lineHeight = Math.floor(fontSize * 1.5);
var height = el.clientHeight;
console.log(Math.ceil(height / lineHeight));

JSFiddle w JQuery |JSFiddle with out JQuery

此代码适用于任何类型的元素:

.HTML:

<div><span class="Text" id="g1" >
                This code works for any Kind of elements: bla blo bli bla blo bli bla blo bli bla blo bli bla blo bli bla blo bli bla blo bli bla blo bli bla blo bli bla blo bli bla blo bli bla blo bli bla blo bli bla blo bli bla blo bli bla blo bli bla blo bli bla blo bli bla blo bli </span>
        </div>

.CSS:

.Text{font-size: 28px;}
@media screen and (max-width: 780px) {
            .Text{font-size: 50px;}
        }

JAVASCRIPT:

function getStyle(el,styleProp)
{
    var x = el;
    if (x.currentStyle)
        var y = x.currentStyle[styleProp];
    else if (window.getComputedStyle)
        var y = document.defaultView.getComputedStyle(x,null).getPropertyValue(styleProp);
    return y;
}
function calculateLineHeight (element) {
  var lineHeight = parseInt(getStyle(element, 'line-height'), 10);
  var clone;
  var singleLineHeight;
  var doubleLineHeight;
  if (isNaN(lineHeight)) {
    clone = element.cloneNode();
    clone.innerHTML = '<br>';
    element.appendChild(clone);
    singleLineHeight = clone.offsetHeight;
    clone.innerHTML = '<br><br>';
    doubleLineHeight = clone.offsetHeight;
    element.removeChild(clone);
    lineHeight = doubleLineHeight - singleLineHeight;
  }
  return lineHeight;
}
function getNumlines(el){return Math.ceil(el.offsetHeight / calculateLineHeight (el))}
console.log(getNumlines(document.getElementById('g1')))

最新更新