在Click上取消动画而不是悬停 - JQuery

时间:2017-12-05 09:07:10

标签: jquery

我只是想知道是否有办法在点击时取消动画而不是悬停。下面的小提琴使用悬停来停止效果。我尝试过类似这种方法的东西,但这里看起来有点不同。

如果您再次单击li,我会想要重置,如果您不再悬停在div上,它会重置。当您点击li时,它将启动动画。

http://jsfiddle.net/htmlboy/qQyhE/

JQuery代码

//animate with no stop()

$(".nostop li").hover(
  function () {
      $(this).animate({width:"100px"},500);
  },
   function () {
    $(this).animate({width:"80px"},500);
  } 
);

//animate with stop()
$(".stop li").hover(
  function () {
      $(this).stop().animate({width:"100px"},500);
  },
   function () {
    $(this).stop().animate({width:"80px"},500);
  } 
);

2 个答案:

答案 0 :(得分:0)

请找到以下解决方案:

//animate with no stop()
$(".nostop li").on("click",function(){
 if( $(this).width() == "100")
    $(this).animate({width:"80px"},500);
    else
     $(this).animate({width:"100px"},500);
  }
);

//animate with stop()
$(".stop li").on("click",function(){
 if( $(this).width() == "100")
    $(this).stop().animate({width:"80px"},500);
    else
    $(this).stop().animate({width:"100px"},500); 
  }
);

http://jsfiddle.net/qQyhE/45/

答案 1 :(得分:0)

我检查元素是否正在设置动画并再次触发.stop().animate()

$(".stop li").click(function() {
  if ($(this).is(':animated')) {
    $(this).stop();
  } else {
    $(this).animate({
      width: "100px"
    }, 1000);
    $(this).animate({
      width: "80px"
    }, 1000);
  }
});

JsFiddle demo