开发者

Showing and hiding in jquery

How can I hide and show a div (and change the width of another div) using the same link,for example I can show A div and change its widht. How can I make it so that if the user clicks again, the width goes back to 600px and the right div is hidden.

 $("a").click(function(event){
         $('#main-content').width(800);
         $('#right').show('slow').slideDown('slow');
         event.preventDefault();
       });

EDIT: From All your replies, I've done this:

 $(document).ready(function(){
   $('#right').hide();
   $('#main-content').width(600);

   $('#show-stats').toggle(function() {
         $('#main-content').width(800);
         $(this).text($(this).text() == 'Show' ? 'Hide' : 'Show');
         $('#right').show('slow').slideDown('slow').fadeIn('slow');
         event.preventDefault();

    }, function() {
         $('#main-content').width(600);
         $(this).text($(this).text() == 'Hide' ? 'Show' : 'Hide');
         $('#right').hide('slow').slideUp('slow').fadeOut('slow'); // change the text开发者_如何学Go
         event.preventDefault();
});



 });

Will this break the internet? Is there a more elegant way or is this fine?


You can use .toggle()

A small example :

$("a").toggle(
    function() {
        $('#main-content').width(800);
        $('#right').show('slow').slidedown('slow');
    },
    function() {
        $('#main-content').width(600);
        $('#right').hide();
    }
);


You need to use the toggle pseudo-event handler. This accepts multiple function definitions as its arguments and calls them in turn, so, given two arguments, the first call will call the first function, the second call the second function, the third call the first function, etc...

$('a').toggle(function(event){
    $('#main-content').width(800);
    $('#right').show('slow').slideDown('slow');
    event.preventDefault();
}, function(event) {
    $('#main-content').width(600);
    $('#right').slideUp('slow').hide('slow');
    event.preventDefault();
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜