你如何只显示div的第一行文本并展开点击?

我想只显示一个包装文本块的第一行,然后在点击时显示整个块。 此外,我想知道如何在第二次点击时将其切换回紧凑的单行版本。

有没有一种简单的方法来通过css + javascript做到这一点? 我使用jQuery。

假设您不想使用任何JavaScript库(这很奇怪 )。

请参阅: http //jsfiddle.net/JUtcX/

HTML:

 

CSS:

 #content { border: 1px solid red; height: 1em; padding: 2px; /* adjust to taste */ overflow: hidden } 

JavaScript的:

 document.getElementById("content").onclick = function() { this.style.height = 'auto'; } 

或者,如果您想使用jQuery之类的JavaScript框架,则可以为其设置动画。

请参阅: http //jsfiddle.net/JUtcX/2/

 $('#content').click(function() { var reducedHeight = $(this).height(); $(this).css('height', 'auto'); var fullHeight = $(this).height(); $(this).height(reducedHeight); $(this).animate({height: fullHeight}, 500); }); 

这很容易使用CSS + JavaScript完成。 您只需将div的高度设置为单行的高度,并隐藏所有溢出。 然后当用户点击div时,使用一个漂亮的动画处理程序执行一个盲目或其他类似的效果来显示div的全部内容。

这是一个非常基本的例子(没有动画): http : //jsfiddle.net/9Lw6T/

 $(document).on('click', '.collapsible', function () { $(this).toggleClass('collapsed'); }); 
 p { cursor: pointer; } .collapsed { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } 
   

I want to show just the first line of a block of wrapped text, and then reveal the whole block on click. Also, I'd like to know how to toggle it back to the compact one-line version on a second click. Is there an easy way to do this through css + javascript? I use jQuery.

 
first line
function toggletext(){ var html= document.getElementById('a').innerHTML; if(html=='first line
'){ html = 'first line
next lines
next lines
'; }else{ html = 'first line
'; } document.getElementById('a').innerHTML = html }

这可以被优化,并且可以使用其中一个公共库

你可以用一些jQuery做到这一点。

 
This is the first line (read more)
This is the rest of the text

脚本

 $('#rest').hide(); $('#first').click(function(){ $('#rest').show(); }); 

http://jsfiddle.net/jasongennaro/dC32A/

在CSS中,将div的大小设置为行的大小(重要的是:您可能需要使用行间距属性以在第二行的底部获得适当的填充)。

我不知道点击,但您可以使用:hover在CSS中:hover以更改样式(重置行间距,重置div大小和溢出到正确的值)以获得hover显示效果。

或者你可以使用JavaScript并在点击时更改CSS(使用jQuery很容易)。

发表我的评论作为答案:

另一种方法是,定义class级height: 1em; overflow-y: hidden; height: 1em; overflow-y: hidden; 然后使用javascript点击添加/删除它。

或者也许您也可以通过将

包装为 -tag来处理:active -pseudo-class,因此不需要javascript。 但是在失去焦点的情况下,div会再次崩溃。

这就足够了:

要隐藏除第一行之外的所有行:

 var theDiv = document.getElementById('theDiv'); theDiv.style.overflowY = 'hidden'; theDiv.style.height = '1em'; 

要显示所有文字:

 var theDiv = document.getElementById('theDiv'); theDiv.style.overflowY = 'visible'; theDiv.style.height = 'auto'; 

或者,如果你要使用jQuery:

 $('#theDiv').css({ height: '1em', overflowY: 'hidden' }); $('#theDiv').css({ height: 'auto', overflowY: 'visible' }); 

将div的隐藏设置为1em然后将其解除为onclick就是解决方案。

检查一下。 我没有使用任何JS库。

CSS

 .expandable{ height:1.2em; overflow:hidden; } 

HTML

  

JS

 window.expand = function(el) { el.style.height = "auto"; } 

这是小提琴

http://jsfiddle.net/RwM8S/1/