如何在单击文本时使用隐藏/显示切换?

时间:2017-12-05 21:30:06

标签: javascript css

我想点击第一行文字,然后展开段落的其余部分。但我也希望能够通过再次单击相同的第一行来关闭文本。我已经为它写了一些代码,但我在JS中非常基础。我很感激能得到这方面的帮助。谢谢。

这是我的JSFiddle:http://jsfiddle.net/JUtcX/868/

$('.expand').each(function() {
  var reducedHeight = $(this).height();
  $(this).css('height', 'auto');
  var fullHeight = $(this).height();
  $(this).height(reducedHeight);

  $(this).data('reducedHeight', reducedHeight);
  $(this).data('fullHeight', fullHeight);
}).click(function() {
  $(this).animate({
    height: $(this).height() ==
      $(this).data('reducedHeight') ? $(this).data('fullHeight') : $(this).data('reducedHeight')
  }, 500);
});
.expand {
  height: 14pt;
  padding: 2px;
  overflow: hidden
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="content" class="expand">
  The day after his forty-eighth birthday was the same day Theo Bitner’s seventy-five-year-old mother Friended him on Facebook. It was also the same day his wife told him he needed to see a doctor. Or a therapist. “It’s your mood,” she said. “It sucks.”
</div>

2 个答案:

答案 0 :(得分:0)

检查这个方式:

$('.expand').click(function(){
    if($(this).hasClass( "open" )){
    $(this).removeClass("open");
  }else{
    $(this).addClass("open");
  }
});

我刚检查段落是否已打开,之后我将内容.open添加或删除到内容中。

css:

.expand {
    max-height: 14pt;
    padding: 2px;
    overflow: hidden;  
    transition: max-height 0.5s;
}

.expand.open{
   max-height: 15em;
}

here the fiddle

希望它可以帮到你。

答案 1 :(得分:0)

您可以尝试切换() http://jsfiddle.net/JUtcX/870/

的jQuery

$('.firstLine').click(function (){
$('.secondLine').toggle();
});

HTML

<div class="firstLine">
The day after his forty-eighth birthday was the same day Theo Bitner’s 
seventy-five-year-old mother Friended him on Facebook.

<div class="secondLine">
It was also the same day his wife told him he needed to see a doctor. Or a 
therapist. “It’s your mood,” she said. “It sucks.” </div>
</div>

CSS

.secondLine {display: none;}