javascript jQuery 幻灯片隐藏和显示相同的按钮

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23685798/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 01:23:03  来源:igfitidea点击:

jQuery slide hide and show same button

javascriptjqueryhtmlcss

提问by jehzlau

I have this simple jquery slide that I want to have only one button. If the div is being shown, the show button will become a hide button. And if the div is hidden, the hide button will become a show button.

我有这个简单的 jquery 幻灯片,我只想有一个按钮。如果正在显示 div,则显示按钮将变为隐藏按钮。如果div被隐藏,隐藏按钮就会变成显示按钮。

Currently, mine has a separate show and hide buttons. I don't know how to merge this buttons into one. I hope someone here can help me. :(

目前,我的有一个单独的显示和隐藏按钮。我不知道如何将这些按钮合二为一。我希望这里有人可以帮助我。:(

    <script type="text/javascript" 
    src="http://code.jquery.com/jquery-1.10.2.js"></script>
    <script type="text/javascript" 
    src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
    <script type="text/javascript" language="javascript">

     $(document).ready(function() {

       $("#hide").click(function(){
          $(".target").hide( "slide", 
                      { direction: "up"  }, 500 );
       });

       $("#show").click(function(){
          $(".target").show( "slide", 
                       {direction: "up" }, 500 );
       });

    });
    </script>
    <style>

      div{ width:100%; 
             height:100px; 
             background: #000; 
             color: #fff; 
         }
   </style>
 </head>

 <div class="target" style="display:none;">
 My Bag Items
 <button id="hide">Hide My Bag</button>
 </div>
 <button id="show">My Bag</button> 

回答by AlienWebguy

$("#toggle").click(function(){
    var $target = $('.target'),
        $toggle = $(this);

    $target.slideToggle( 500, function () {
        $toggle.text(($target.is(':visible') ? 'Hide' : 'Show') + ' My Bag');
    });
});

Demo : http://jsfiddle.net/qmK26/

演示:http: //jsfiddle.net/qmK26/

回答by Jay Blanchard

New markup -

新标记 -

<div class="target">My Bag Items</div>
<button id="togButton">Hide</button>

jQuery

jQuery

$('#togButton').click(function() {
    $('.target').slideToggle(500);
    if( $(this).text() == 'Hide' ) {
        $(this).text('Show');
    } else {
        $(this).text('Hide');
    }
});