获得div内容的第3行

时间:2013-03-01 11:03:20

标签: javascript jquery html dojo

我有一个包含四行内容的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;

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

2 个答案:

答案 0 :(得分: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>

答案 1 :(得分:0)

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

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

警报(结果);