开发者

Jquery Click Btn Fade in/out

I am working on a website that requires a btn that removes the entire middle section when clicked to reveal a nice 100% background image. I have set up a standard HTML btn with an id of show-background and I also a div with an id of content-are开发者_运维问答a. My jQuery code looks like this:

$("a#show-background").click(function () {
    $("div#content-area").fadeOut("slow");
});

$("a#show-background").click(function () {
    $("div#content-area").fadeIn("slow");
});

This isn't working right. I wonder if anyone can put me on the right lines? Many thanks in advance!


Like Emil Ivanov wrote, the two event handlers push out each other, so if you want to toggle the visible state of the div with the same anchor, use the toggle method:

$("a#show-background").click(function() {
    $("div#content-area").toggle("slow");
});


Do you mean toggling?

$("a#show-background").toggle(
    function () {
        $("div#content-area").fadeOut("slow");
    },
    function () {
        $("div#content-area").fadeIn("slow");
    }
);


Try something like this, currently you're hiding/showing at the same time resulting in nothing:

$("a#show-background").click(function () {
    $("div#content-area:visible").stop().fadeOut("slow");
    $("div#content-area").not(":visible").stop().fadeIn("slow");
});

This will hide if it's visible, show if it's not...and if clicked mid-way, stop the current animation and start going the other way.


You say that your code uses a button. Since I can't see your html I'll assume you're using either an input tag or a button tag and not an anchor tag. In any case try changing your selector to this.

$("#show-background")

Also as Emil Ivanov mentioned your calls are canceling each other out. A way around this is to do the following. Assuming that what it is you're hiding is to be shown initially...

$("#show-background").click(function () {
  if ($("#content-area").hasClass("bg_hidden")){
    $("#content-area")
      .removeClass("bg_hidden")
      .stop()
      .fadeIn("slow");

    $("#show-background").text("Hide Me Text");
  }
  else{
    $("#content-area")
      .addClass("bg_hidden")
      .stop()
      .fadeOut("slow");

    $("#show-background").text("Show Me Text");
  }
});


if you want to achive the same fadeIn/Out effect then

$("#show-background").click(
             function(){ 
                        $("div#content-area').animate({opacity: 'toggle'}, 'slow'); 
                       }
              );

would do it ..


jQuery 1.4.4 or higher can use

$('#show-background').click(function () {
    $('div#content-area').fadeToggle('slow');       
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜