jQuery动画

1.show() 和 hide() 方法
show() 和 hide() 方法是 jQuery 中最基本的方法,他们的作用是对某一或某些元素的显示或隐藏:
$("#input").focus(function(){
  
$(this).hide();
});
$("#input").blur(function(){
  $(this).show();
}););

上段代码的作用是当 id 为 input 的元素得到焦点则隐藏,失去焦点则显示。要实现根据时间的动画效果,我们仅需要在 show() 和 hide() 方法中传入参数即可,参数有 slow、normal、fast 等字符串参数,或者直接传入动画持续时间的毫秒数。我们可以将代码改写如下实现优雅的动画效果:

$("#input").focus(function(){

   $(this).hide(2000);

});

$("#input").blur(function(){

   $(this).show("fast");

});

2.fadeIn()、fadeOut()、slideDown() 和 slideUp() 方法

fadeIn() 与 fadeOut() 方法是仅仅通过改变元素的透明度来实现显示与隐藏的过渡的。slideDown() 与 slideUp() 则是通过改变元素的高度实现显示与隐藏的动画。参数与show()、hide() 的参数相同。

3.自定义动画 animate() 方法

实际使用过程中,上述的几种动画特效都不一定能够满足需求,所以 jQuery 提供了自定义动画的方法 animate() 以满足对特定动画效果的需求。

animate() 方法可以接受三个参数,其中后两个参数是可选的:animate(params,speed,callback);

params 参数是动画作用后的最终效果,如 {background:"#eeeeee",color:"#ffffff"};

speed 参数顾名思义就是动画的持续时间;

callback 参数是执行这个动画后执行的方法,即回调方法。

示例如下:

var input_function = function(){

  $("#input").val("请输入");

}

var $width;

var $height

$("#input").focus(function(){

  $width = $(this).css("width");

  $height = $(this).css("height");

  $(this).animate({"80%",height:"100px"},500,function(){

  $(this).val("");

  });

});

$("#input").blur(function(){

  $(this).animate({$width,height:$height},500,input_function);//使用已经定义好了的方法;

});

$("#input").blur();//页面加载结束即调用 #input 的 blur 事件;

上面的动画效果可以看到 width 和 height 的改变是同步的,有时候我们需要先改变 width ,再改变 height ,这是我们应该分解 width 和 height 形成多个 animate() 动画,多个 animate() 动画是依次执行的:

var input_function = function(){

  $("#input").val("Please input here..");

}

var $width;

var $height

$("#input").focus(function(){

  $width = $(this).css("width");

  $height = $(this).css("height");

  $(this).animate({"80%"},500,function(){

  $(this).val("");

  }).animate({height:"100px"},500);

});

$("#input").blur(function(){

  $(this).animate({height:$height},500,input_function).animate({$width},500);

});

$("#input").blur();

4.停止动画 stop() 方法

上面的动画的例子效果挺玄,但是当我们很野蛮的不停的让 #input 得到焦点、失去焦点、得到焦点、失去焦点…依次反复,不过几轮就会发现 jQuery 的动画特效杯具了,卡在那儿动不了了。因为我们在执行得到焦点的动画的过程中又让元素是去焦点,结果在执行得到焦点的动画之后又要执行是去焦点的动画,反反复复,jQuery 就晕了。

解决这个问题,我们可以通过调用 stop() 方法在执行下一个动画之前结束未完成的动画:

var input_function = function(){

  $("#input").val("Please input here..");

 }

var $width;

var $height;

$("#input").mouseover(function(){

  $width = $(this).css("width");

  $height = $(this).css("height");

  $(this).stop().animate({"80%"},500,function(){

    $(this).val("");

    });

});

$("#input").mouseout(function(){

  $(this).stop().animate({$width},500,input_function);

});

$("#input").blur();

有人或许会问,怎么不依次实现两个 animate() 动画了呢?那样效果炫多了!也有人可能是认为这是为了节省页面。其实真正的原因是因为如果现在依次实现多个 animate() 动画的时候会杯具。自己可以试试。解决办法是给 animate() 传入一个参数:true 实现多个 animate() 动画的共存。

jQuery动画比css方便很多,用得好的画可以做出很多赏心悦目的效果,这也是我觉得jQuery最好玩的地方之一。

原文地址:https://www.cnblogs.com/mayicom/p/3944941.html