如何在按钮单击时动画我的div滑出

我有一个问题,我设法得到一些代码,使div元素滑入视图但如果单击关闭按钮,如何让它再次向下滑动? 所以我可以继续按下链接,它将再次播放动画,而不是只显示div已经在其最终位置。

inheritance了jquery代码

$(document).ready(function() { //select all the a tag with name equal to modal $('a[name=modal]').click(function(e) { //Cancel the link behavior e.preventDefault(); //Get the A tag var id = $(this).attr('href'); //Get the screen height and width var maskHeight = $(document).height(); var maskWidth = $(window).width(); //Set height and width to mask to fill up the whole screen $('#mask').css({'width':maskWidth,'height':maskHeight}); //transition effect $('#mask').fadeIn(600); //Get the window height and width var winH = $(window).height(); var winW = $(window).width(); //Set the popup window to center $(id).css('top', winH/2-$(id).height()/2); $(id).css('left', winW/2-$(id).width()/2); //Slide up Boxes Div transition effect $(id).css({display:'block'}).animate({marginTop:'0px', opacity:'1', },400); }); //if close button is clicked $('.window .close').click(function (e) { //Cancel the link behavior e.preventDefault(); $('#mask, .window').hide(); }); //if mask is clicked $('#mask').click(function () { $(this).hide(); $('.window').hide(); }); }); 

谢谢

您可以执行与向上滑动元素相反的操作:

 $('.window .close').click(function (e) { //Cancel the link behavior e.preventDefault(); $(this).closest('.window').animate({ marginTop : 1200, opacity : 0 }, 400, function () { $(this).css('display', 'none'); }); }); 

您的代码中存在一些错误:

  1. .animate({marginTop:'0px', opacity:'1', },400)有一个尾随的逗号,它会在Internet Explorer中强制出错,它应该是: .animate({marginTop:'0px', opacity:'1' },400)
  2. 你在同一个元素上连续两次调用.css ,你可以将一个对象传递给.css函数,就像你在代码中进一步向下传递一样:

 $(id).css({ top : winH/2-$(id).height()/2, left : winW/2-$(id).width()/2, display : 'block' }).animate({marginTop:'0px', opacity:'1' },400); 

注意我还链接了.animate()函数调用,这样你只需选择$(id)一次。

.slideUp()和.slideDown()

你知道jQuery已经有了这样做的function吗?

  • .slideUp() : http : .slideUp()
  • .slidedown() : http : .slidedown()
  • .slideToggle() : http : .slideToggle()

UPDATE

这是你的jsfiddle的更新版本: http : //jsfiddle.net/4hw8H/1/

 $(function() { $('a[name=modal]').click(function(e) { e.preventDefault(); var $this = $($(this).attr('href')), winH = $(window).height(), winW = $(window).width(), maskHeight = $(document).height(), maskWidth = $(window).width(); $('#mask').css({ width : maskWidth, height : maskHeight }).fadeIn(600); $this.css({ top : winH / 2 - $this.height() / 2, left : winW / 2 - $this.width() / 2, display : 'block' }).animate({ marginTop : 0, opacity : 1 }, 400); }); $('.window .close').click(function (e) { e.preventDefault(); $(this).closest('.window').animate({ marginTop : 1200, opacity : 0 }, 400, function () { $(this).css('display', 'none'); }); $('#mask').fadeOut(600); }); $('#mask').click(function () { $('.window .close').trigger('click'); }); });