Animate.css - 将onmouseover应用于div以添加类

时间:2018-03-15 11:17:25

标签: javascript jquery css

我已经导入了animate.css类,它在给出类名时非常有效,但是当将鼠标悬停在div上时使用应用函数来更改类时它不起作用

  <div id="result" style="width: 100px; height: 100px; background-color: blue; color: white" >
            animated bounce
        </div>

这是脚本

<script>
function animationHover(element, animation) {
    element = $(element);
    element.hover(
        function () {
            element.addClass('animated ' + animation);
        },
        function () {
            //wait for animation to finish before removing classes
            window.setTimeout(function () {
                element.removeClass('animated ' + animation);
            }, 2000);
        }
    );
};
</script>

然后最后调用方法:

animationHover('#result', 'tada');

但这并没有做任何事情

感谢所有帮助

1 个答案:

答案 0 :(得分:3)

您可以这样简化:

function animationHover(element, animation) {
  $(element).hover(
    function() {
      $(this).addClass('animated ' + animation);
    },
    function() {
      //wait for animation to finish before removing classes
      window.setTimeout(function() {
        $(element).removeClass('animated ' + animation);
      }, 1000);
    }
  );
};
animationHover('#result', 'tada');
.animated {
  animation: anime 2s forwards;
}

.tada {
  background: blue;
  color: red;
}

@keyframes anime {
  to {
    transform: rotate(90deg);
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result" style="width: 100px; height: 100px;">
  animated bounce
</div>

或类似的东西:

function animationHover(element, animation) {
  $(element).hover(
    function() {
      $(this).addClass('animated ' + animation)
      .on('animationend',function() {
        $(this).removeClass('animated ' + animation)
      });
    }
  );
};
animationHover('#result', 'tada');
.animated {
  animation: anime 2s forwards;
}

.tada {
  background: blue;
  color: red;
}

@keyframes anime {
  to {
    transform: rotate(90deg);
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result" style="width: 100px; height: 100px;">
  animated bounce
</div>