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

dan*_*dan 18 javascript css jquery

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

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

thi*_*dot 15

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

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

HTML:

<div id="content"></div>
Run Code Online (Sandbox Code Playgroud)

CSS:

#content {
    border: 1px solid red;
    height: 1em;
    padding: 2px; /* adjust to taste */
    overflow: hidden    
}
Run Code Online (Sandbox Code Playgroud)

JavaScript的:

document.getElementById("content").onclick = function() {
    this.style.height = 'auto';
}
Run Code Online (Sandbox Code Playgroud)

或者,如果您想使用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);
});
Run Code Online (Sandbox Code Playgroud)

  • 我已经把它加了一点并添加了一个切换:http://jsfiddle.net/JUtcX/4/ (4认同)

aro*_*oth 8

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

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


Qwe*_*tiy 6

$(document).on('click', '.collapsible', function () {
  $(this).toggleClass('collapsed');
});
Run Code Online (Sandbox Code Playgroud)
p {
  cursor: pointer;
}

.collapsed {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<p class="collapsible collapsed">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.</p>
<p class="collapsible">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.</p>
<p class="collapsible collapsed">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.</p>
Run Code Online (Sandbox Code Playgroud)