簡體   English   中英

響應按鈕單擊顯示和隱藏文本

[英]Showing and hiding text in response to a button click

下面的代碼就是這樣做的。 當我第一次單擊按鈕時,它會顯示相應的文本。 當我再次單擊同一個按鈕時,它會淡出並淡入。但是,如果第二次單擊該按鈕,我希望相應的文本消失,而不是淡出然后淡入。

$(document).ready(function(){
    $('.info').click(function(){
        $(this).next().fadeOut("slow");
    $(this).next().fadeIn("slow");
    });
});

HTML:

    <div>
        <a class="info" p style="font-size:30px" href="javascript:void(0);">header 1</a>
        <h1 class="infoText" style="display:none">text 1</h1>
    </div>
    <div>
        <a class="info" href="javascript:void(0);">header 2</a>
        <h1 class="infoText" style="display:none">text 2</h1>
    </div>
    <div>
        <a class="info" href="javascript:void(0);">header 3</a>
        <h1 class="infoText" style="display:none">text 3</h1>
    </div>

它應該像這樣開始:

標題1

標題2

標題3

當我單擊 header1 時,它應該是這樣的:

標題1

文本1

標題2

標題3

當我再次單擊標題 1 時,它應該是這樣的:

標題1

標題2

標題3

有人知道怎么做嗎?

您可以使用fadeToggle()使用淡入淡出效果切換顯示

 $(document).ready(function() { $('.info').click(function() { $(this).next().fadeToggle("slow"); }); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div> <a class="info" p style="font-size:30px" href="javascript:void(0);">header 1</a> <h1 class="infoText" style="display:none">text 1</h1> </div> <div> <a class="info" href="javascript:void(0);">header 2</a> <h1 class="infoText" style="display:none">text 2</h1> </div> <div> <a class="info" href="javascript:void(0);">header 3</a> <h1 class="infoText" style="display:none">text 3</h1> </div>

為此,您可以使用 toggle()。 如果元素已經顯示,它將隱藏該元素,否則它將顯示該元素。

$('.info').click(function(){
     $(this).next().toggle("slow");
 });
$('.info').click(function(){
    //$(this).next().fadeOut("slow");
    $(this).next().toggle("slow");
});

使用切換來隱藏和顯示某些東西

根據@Tushar 的建議

$('.info').click(function(){
    //$(this).next().fadeOut("slow");
    $(this).next().fadeToggle("slow");
});

您可以使用 toggle() 函數:

$(document).ready(function() {
  $('.info').click(function() {
    $(this).next().fadeToggle("slow");
  });
});

演示

你試試這個代碼

$(document).ready(function() {
  $('.info').click(function() {
      var _self = $(this);

      if(_self.hasClass("active")) {
          _self.next().fadeOut("slow");
         _self.removeClass("active");
      } else {
           _self.next().fadeIn("slow");         
          _self.addClass("active");
      }

  });
});

工作演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM