如何简化jquery动画函数代码

how to simplify jquery animation function code

本文关键字:函数 代码 动画 jquery 何简化      更新时间:2023-09-26

我有两个函数来制作一些动画效果,如何简写这个函数并将其更改为简单的代码?

   $('.box-1').hover(function() {
    $('.box-1').stop().animate({bottom:'0'});
    $('.dul-1').stop().animate({top:'0px'});
},
function() {
  $('.box-1').stop().animate({bottom:'-100px'});
  $('.dul-1').stop().animate({top:'-100px'});
   });
$('.box-2').hover(function() {
    $('.box-2').stop().animate({bottom:'0'});
    $('.dul-2').stop().animate({top:'0px'});
},
function() {
  $('.box-2').stop().animate({bottom:'-100px'});
  $('.dul-2').stop().animate({top:'-100px'});
   });

小提琴链接

检查我更新的FIDDLE。将数据索引属性添加到.boxdiv。因此,当悬停事件调用脚本时,将使用$(this).attr('data-index');获取索引;。

HTML:

<div class="wrapper">
  <div class="dul-1"></div>
  <div class="dul-2"></div>
  <div class="box box-1" data-index="1"></div>
  <div class="box box-2" data-index="2"></div>
</div>

Javascript:

$('.box').hover(function() {
    index = $(this).attr('data-index');
    $('.box-'+index).stop().animate({bottom:'0'});
    $('.dul-'+index).stop().animate({top:'0px'});
 },
 function() {
    $('.box-'+index).stop().animate({bottom:'-100px'});
    $('.dul-'+index).stop().animate({top:'-100px'});
   }
 );