2013-12-16 45 views
-3

我有一个文本里面的div。要求是,如果文本长度超过3行,则隐藏文本的其余部分并显示“more ..”链接。 (更多的链接必须附加到可见的文本,而不是显示在一个新的行)显示更多/较少的链接

点击更多的链接将使div展开显示整个文本块,“更多..”链接将更改为“更少...”。

点击less会再次将文本折叠回3行,更多链接将重新出现。

这应该只发生在文本长度超过3行的情况下。

我尝试使用字符数来追加更多链接,但是这对于响应式设计会成为问题。即使在手机,平板电脑上,用户也不应该看到超过3行的文字。

这是我到目前为止。

$('.notesDiv').each(function(div) { 
       var content = $(this).html(); 

       if (content.length > 550) { 
        content = content.substr(0, 550); 
        content += ' <a href="#" class="showMore">More...</a>'; 

        $(this).html(content); 
       } 
      }); 
+0

试试这个:http://viralpatel.net/blogs/dynamically-shortened-text-show-more-link-jquery/ – Hariprasad

+1

我知道这个问题已经关闭,但我为你创建了一个小提琴来做到这一点,请参阅:http: //jsfiddle.net/NwAL8/ - 它使用近似行高来计算最小高度,您应该在CSS中指定实际行高以便更好地计算。 – SW4

+0

我已经添加了我的代码样本,并希望能够重新打开该问题。 – iDesi

回答

1

看到这个FIDDLE

HTML

<div class='item'>"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. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</div> 

jQuery的

function collapse(item) { 

    var lineHeight = item.css('line-height') !== 'normal' ? parseInt(item.css('line-height')) : parseInt(item.css('font-size')) * 3.7; 
    var height = item.height(); 
    if (lineHeight < height) { 
     item.css({ 
      'height': lineHeight + 'px', 
      overflow: 'hidden' 
     }); 
     item.children('a.toggle').length == 0 && item.append("<a href='#' class='toggle'>(more)</a>"); 
    } 
} 

$('div.item').each(function() { 
    collapse($(this)); 
}); 


$('a.toggle').click(function (event) { 
    event.preventDefault(); 

    var toggle = $(this); 
    var item = toggle.parent('div'); 
    if (toggle.text() == '(more)') { 
     toggle.text('(less)'); 
     item.css({ 
      'overflow': 'auto', 
      'height': 'auto' 
     }); 
    } else { 
     toggle.text('(more)'); 
     collapse(item); 
    } 
}); 

CSS

div.item { 
    display:inline-block; 
    max-width:300px; 
    border:1px solid grey; 
    position:relative; 
    min-height:10px; 
} 
a.toggle { 
    position:absolute; 
    bottom:0px; 
    right:0px; 
    display:inline-block; 
    background:white; 
    padding-left:10px; 
} 
相关问题