[英]How can I adjust this javascript code so an animation is activated whenever the mouse hovers over the element?
So I used this code from Justin Aguilar's CSS3 Animation Cheat Sheet to activate an animation on a button when I hover over it: 因此,我将鼠标悬停在Justin Aguilar的CSS3动画备忘单上的以下代码来激活按钮上的动画:
<div id="object" class="pulse">
<script>
$('#animatedElement').hover(function() {
$(this).addClass("pulse");
});
</script>
The problem is that the animation just continues even when I am no longer hovering over the button. 问题在于,即使我不再将鼠标悬停在按钮上,动画也只会继续播放。 What can I do to make a button animate every time a user hovers over it, but stop when they move the mouse away? 每当用户将鼠标悬停在按钮上方时,该怎么做才能使其具有动画效果,而当用户将鼠标移开时会停止动画? Whenever I tried to tweak it with anything involving .stop, it just keeps the animation from playing at all. 每当我尝试对涉及.stop的任何内容进行调整时,它都根本无法播放动画。
I am new to coding and this has been a huge pain today, so any help would be very much appreciated! 我是编码的新手,今天这是一个很大的痛苦,因此,非常感谢您的帮助! Thanks! 谢谢!
You don't need JavaScript for that at all. 您根本不需要JavaScript。 Use CSS selectors. 使用CSS选择器。 #animatedElement:hover in your case. #animatedElement:悬停在您的情况下。
Here you go with one more solution 在这里,您还有另外一种解决方案
$('#animatedElement').hover(function() { $(this).addClass("pulse"); }).mouseleave(function(){ $(this).removeClass("pulse"); });
.pulse { background: #000; color: #fff; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="animatedElement">Hover Me!!!</div>
Hope this will help you. 希望这会帮助你。
the hover()
method accepts two callbacks: one for when the mouse enters the html element, and one for when it leaves. hover()
方法接受两个回调:一个用于鼠标何时进入html元素,另一个用于何时离开。 Therefore, you could simply add another callback to your function to remove the "pulse" class. 因此,您可以简单地向函数添加另一个回调以删除“ pulse”类。
$('#animatedElement').hover(function() {
$(this).addClass("pulse");
},
function(){
$(this).removeClass("pulse");
});
Alternatively, you could just go with Alex's excellent answer. 另外,您也可以选择Alex的出色答案。
You can use CSS to make an animation, for example, in this code: 您可以使用CSS制作动画,例如,在以下代码中:
.pulse {
background: GREEN;
border-radius: 6px
transition-property: background, border-radius;
transition-duration: 1s;
transition-timing-function: linear;
}
.pulse:hover {
background: BLACK;
border-radius: 50%;
}
You have set in css the start properties for the element, and transition declaration, in this example i'm going to do a transition in the background and the radius properties when hover on a element with pulse class. 您已经在css中设置了元素的开始属性和过渡声明,在此示例中,当将鼠标悬停在具有脉冲类的元素上时,我将在背景和半径属性中进行过渡。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.