jQuery onclick addclass/removeclass and add fade

为君一笑 提交于 2019-12-07 16:57:46

问题


The past three day I have been searching for a solution to my problem. I have seen a lot of people with the same question as I have, but not one solution fixes my problem. So I am again where I started and I am asking for the help of you friendly people!

I now have the following script running that works perfect for me:

$(".show_commentsandnotes_container").click(function () {
    $('.commentsandnotes_bg').addClass('show');
    $('.commentsandnotes_container').addClass('show');
});
$(".commentsandnotes_bg").click(function () {
    $('.commentsandnotes_bg').removeClass('show');
    $('.commentsandnotes_container').removeClass('show');
});

The only thing I can't get to work, is the fading in and out of elements. I have tried a lot of solution like toggle and show/hide, but this works the best for me. The only simple thing that I need is that fading is added to the script (1000 ms), I just can't work that out.

Can someone help me? Thanks in advance.


回答1:


$(".show_commentsandnotes_container").click(function () {
    $('.commentsandnotes_bg').fadeIn(1000, function() {
       $('.commentsandnotes_bg').addClass('show');
    });
    $('.commentsandnotes_container').fadeIn(1000, function() {
       $('.commentsandnotes_container').addClass('show');
    });
});
$(".commentsandnotes_bg").click(function () {
    $('.commentsandnotes_bg').fadeOut(1000, function() { 
       $('.commentsandnotes_bg').removeClass('show');
    });
    $('.commentsandnotes_container').fadeOut(1000, function() { 
       $('.commentsandnotes_container').removeClass('show'); 
    });
});

As a side note, for more complex scenarios, a more controllable alternative is to use jQuery.animate(). Just be sure to really look into the documentation and know exactly what you want before diving into this. It is much more flexible, but not nearly as straightforward.

For example, an untested version of part of the code provided in the question :

$( "#show_commentsandnotes_container" ).click(function() {
  $("#commentsandnotes_bg" ).animate({
    opacity: 0.25,
    height: "toggle"
  }, 1000, function() {
     $("#commentsandnotes_bg").addClass("show");
  });
});


来源:https://stackoverflow.com/questions/23414413/jquery-onclick-addclass-removeclass-and-add-fade

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!