这里有很多非常相似的问题,但我找不到我的问题的确切答案。
我是 jQuery .animate()
方法的新手,我想知道是否有常见或最佳的反转动画的方法?
这是我想出的一个例子的 fiddle : Fiddle
基本上它所做的就是使用 if 语句来检查一个 CSS 属性,然后将其设置为一种状态或返回另一种状态。
$(document).ready(function () {
$("[name=toggle]").on("click", function () {
if ($('.box').width() < 125) {
$(".box").animate({
opacity: .3,
width: "125px",
height: "125px"
}, 250);
} else {
$(".box").animate({
opacity: 1,
width: "100px",
height: "100px"
}, 250)
}
});
});
.box {
background-color: lightblue;
box-shadow: 5px 5px 10px #000000;
width: 100px;
height: 100px;
display: block;
margin: 20px auto 0 auto;
border-radius: 25px;
}
[name="toggle"] {
display: block;
margin: 0 auto;
margin-top: 15px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<button name="toggle">Animate</button>
<div class="box"></div>
这是我第一次接触 .animate() 时能够想到的,但我认为可能有更好的方法。 假设您想在悬停时播放动画,并在鼠标离开元素时反转动画。有没有办法轻松轻松地反转 jQuery 动画?我不在,我可以在 CSS 中使用 :hover 状态,但这是一个关于 jQuery .animate() 的假设性问题。
最佳答案
您可以使用带有过渡效果的纯 CSS 来做到这一点。
.animate-me {
background-color:red;
width:50px;
height:50px;
position:absolute;
top:0;
left:150px;
transition:left 2s, background-color 2s;
}
.animate-me:hover{
left:0;
background-color:blue;
}
<div class="animate-me"></div>
通常css比较简单。但是,当浏览器较旧时,jquery 可能是您唯一的方式,因此我包含了 JQuery 方式。
function animationForward(){
$(".animate-me").animate(
{
opacity: 0.25,
left: "100",
height: "100"
}, 5000, function() {
animationBackward();
}
)}
function animationBackward(){
$(".animate-me").animate(
{
opacity: 1,
left: "50",
height: "50"
}, 5000, function() {
animationForward();
}
)}
animationForward();
.animate-me {
width:50px;
height:50px;
background-color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="animate-me"></div>
关于javascript - 如何将 jQuery 动画反转回原始 CSS 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33535055/