开发者

use javascript to get only the visible content in a span

I have a specific requirement to get the exact content of first three lines displayed in a span tag. If content in span exceeds three lines, only first three lines should be displayed, the rest of the content text should be clipped.

Using javascript I have completed till clipping of text after 3 lines开发者_如何学运维. Now I need to get the text displayed in the first 3 lines of the span tag. Any help ?

<html>  
<body>  
<script type="text/javascript">  
function getHeight(){  
 document.getElementById('many').style.height = document.getElementById('simple').scrollHeight*3;  
document.getElementById('many').style.overflow = 'hidden';  
}  
</script>  
<span style='display:block' id='simple'>Single Line</span>  
<span style='display:block' id='many'>
Mutli Line Multi Line Mutli Line Mutli Line Mutli Line Mutli Line Mutli Line Mutli Line
Mutli Line Multi Line Mutli Line Mutli Line Mutli Line Mutli Line Mutli Line Mutli Line
Mutli Line Multi Line Mutli Line Mutli Line Mutli Line Mutli Line Mutli Line Mutli Line
Mutli Line Multi Line Mutli Line Mutli Line Mutli Line Mutli Line Mutli Line Mutli Line
Mutli Line Multi Line Mutli Line Mutli Line Mutli Line Mutli Line Mutli Line Mutli Line
Mutli Line Multi Line Mutli Line Mutli Line Mutli Line Mutli Line Mutli Line Mutli Line
Mutli Line Multi Line Mutli Line Mutli Line Mutli Line Mutli Line Mutli Line Mutli Line
</span> 
 <br>
 <input type='button' onclick='getHeight()' value='click this to trim multi line'/>
</body>  
</html>


I would recommend using jQuery for this. If the content doesn't actually need to be removed from the page, you can hide it using overflow: hidden;. The jQuery to do this would be quite simple too:

<script type="text/javascript">
$(function()
{
    // Get the line height and multiply it by 3
    var three_lines = $('#many').css('line-height').replace(/[^0-9.]+/, '')*3;
    // Resize the span
    $('#many').css( {'display': 'block', 'height': three_lines, 'overflow': 'hidden'} );
});
</script>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜