得到第三行的最后一句话

时间:2015-01-24 01:17:46

标签: javascript

我找到了一个脚本,它输出段落中每行的最后一个单词。有人可以帮忙只输出第三行的最后一个字吗?

<div id="flop">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.</div>

<script>
var d = document.getElementById('flop');
var t = d.innerHTML;
var w = t.split(' ');       

d.innerHTML = w[0];
var height = d.clientHeight;
for(var i = 1; i < w.length; i++){
    d.innerHTML = d.innerHTML + ' ' + w[i];

    if(d.clientHeight > height){
        height = d.clientHeight;
        console.log(w[i-1]);
    }
}
</script>

1 个答案:

答案 0 :(得分:1)

使用计数器

d.innerHTML = w[0];
var lineCount = 1;
var height = d.clientHeight;
for(var i = 1; i < w.length; i++){
    d.innerHTML = d.innerHTML + ' ' + w[i];

    if(d.clientHeight > height){
        height = d.clientHeight;
        if (lineCount == 3) {
            console.log(w[i-1]);
        }
        lineCount++;
    }
}

将其包装在<div>

for(var i = 1; i < w.length; i++){
    d.innerHTML = d.innerHTML + ' ' + w[i];

    if(d.clientHeight > height){
        height = d.clientHeight;
        if (lineCount == 3) {
            d.innerHTML = d.innerHTML.replace(/\b([^ ]*) ([^ ]*)$/, '<div>$1</div> $2');
            console.log(w[i-1]);
        }
        lineCount++;
    }
}

请注意,添加DIV可能会更改布局,这可能会改变最后的单词。