0

我有一个四行内容的 div。我可以使用以下代码获取行数。但我的要求是获取 div 的 4 行文本。例如:

<div>
   ut returns between paragraphsut returns between paragraphs
   ut returns between paragraphsut returns between paragraphs
   web ui text is going on hereut returns between paragraphsut 
   returns between paragraphs
</div>

在上面的 DIV 中。我想得到第 4 行文本,即在段落之间返回。有没有办法做到这一点。

我得到了以下代码的行数

var content = elm.innerHTML;     
var elmHeight = elm.offsetHeight;
var lineHeight = 15;
var lines = elmHeight / lineHeight;

行变量具有特定 DIV 中的行数

4

2 回答 2

0

var line_number=3; // 你喜欢的行号

var result= $.trm( $( '#mydiv' ).text() ).split( '\n' )[line_number];// mydiv 是划分的id

警报(结果);

于 2013-03-01T11:45:40.720 回答
0

以下对我来说适用于 Firefox。我希望它也可以被采用在 IE 下工作。

<html>
  <head>
    <script language="javascript">
<!--

function find3rdline (element)
{
    var text = element.textContent;

    var begin = -1;
    var end = -1;
    var top = -1;
    var line = -1;
    for (i = 0; i < text.length; i++)
    {
        var id = "marker" + i;
        element.innerHTML = text.substr (0, i) + "<span id='" + id + "'>X</span>" + text.substr (i, text.length - i);
        var marker = document.getElementById (id);
        if (marker.offsetTop != top)
        {
            top = marker.offsetTop;
            line++;
            if (line == 2) begin = i;
            else if (line == 3)
            {
                end = i;
                // break;
            }
        }
    }

    element.innerHTML = text;

    if (begin == -1) return "";
    else if (end == -1) return text.substr (begin, text.length - begin);
    else return text.substr (begin, end - begin);
}

// -->
    </script>
  </head>
  <body onload="alert ('Third line is: [' + find3rdline (text) + ']')">
    <div id="text">
      Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce porttitor, leo non sollicitudin blandit, metus eros dapibus massa, nec euismod nunc sapien quis nunc. Maecenas mollis, justo sed egestas semper, nulla libero blandit sem, eget gravida ante sapien sagittis turpis. Vivamus sit amet elit tortor, a eleifend mi. Aliquam erat volutpat. Vestibulum sit amet pellentesque magna. Integer eget erat nisl. Suspendisse adipiscing placerat felis quis blandit. Etiam hendrerit tincidunt gravida. Nunc condimentum tristique commodo. Aliquam eget tellus et sapien accumsan cursus.  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce porttitor, leo non sollicitudin blandit, metus eros dapibus massa, nec euismod nunc sapien quis nunc. Maecenas mollis, justo sed egestas semper, nulla libero blandit sem, eget gravida ante sapien sagittis turpis. Vivamus sit amet elit tortor, a eleifend mi. Aliquam erat volutpat. Vestibulum sit amet pellentesque magna. Integer eget erat nisl. Suspendisse adipiscing placerat felis quis blandit. Etiam hendrerit tincidunt gravida. Nunc condimentum tristique commodo. Aliquam eget tellus et sapien accumsan cursus.
    </div>
  </body>
</html>
于 2013-03-01T11:37:14.613 回答