我在我的網(wǎng)站上有一個(gè)動(dòng)畫,當(dāng)鼠標(biāo)懸停時(shí),它的寬度從100像素到800像素。
但是當(dāng)懸停時(shí),它只是轉(zhuǎn)到正常位置,沒有動(dòng)畫。
我怎樣才能讓動(dòng)畫像在懸停時(shí)一樣回到懸停時(shí)的狀態(tài)呢?
我只找到了過渡的解決方案,但我需要它來制作動(dòng)畫。
<div id="blackbox"/>
<div id="blacktxt">
Navigation
</div>
看這里
為什么不用轉(zhuǎn)場代替動(dòng)畫?JSFiddle演示
#blackbox {
background: black;
width: 100px;
height: 80px;
color: white;
text-align: center;
font-family: Times;
font-size: 20px;
position: fixed;
left: 0px;
bottom: 100px;
opacity: 0.5;
margin-bottom: 10px;
transition: all 2s; /* Add this transition */
}
#blackbox:hover { /* Apply the new design on hover */
opacity: 0.8;
width: 800px;
}
#blacktxt {
margin-top: 10px;
height: 60px;
transition: opacity 0.5s, width 5s;
position: absolute;
font-family: cursive;
cursor: default;
}
#blacktxt:hover {
opacity: 0;
}
<div id="blackbox">
<div id="blacktxt">
Navigation
</div>
</div>
如果您需要CSS動(dòng)畫在過渡中提供的附加功能,可以使用普通javascript Web動(dòng)畫API和playbackRate屬性無縫反轉(zhuǎn)CSS動(dòng)畫。
下面是代碼(注意,您只需在css中指定一個(gè)動(dòng)畫):
let el = document.querySelector('.el');
// play animation on mouseenter
el.addEventListener('mouseenter', function () {
// force animation again if already triggered
el.classList.remove('animate');
// hack trigger a DOM reflow to reinit animation
void el.offsetWidth;
//trigger animation
el.classList.add("animate");
}, false);
// reverse animation on mouseout
el.addEventListener('mouseout', function () {
playReverse(el);
}, false);
function playReverse(el) {
let ani = el.getAnimations()[0];
if(!ani) {
return;
}
ani.playbackRate = -1;
ani.play();
}
.el {
height: 100px;
width: 100px;
background: black;
animation-duration: 6s;
animation-fill-mode: forwards;
}
.animate {
animation-name: transforms;
}
@keyframes transforms {
0% {
transform: translate(0, 0);
}
100% {
transform: translate(400px, 0);
}
}
<div class='el'></div>
我為此編寫了jQuery可逆插件。它相對于CSS轉(zhuǎn)換的主要優(yōu)勢是它可以在IE9和更老的瀏覽器上工作。
你可以通過轉(zhuǎn)場本身來代替動(dòng)畫
#blackbox {
width: 100px;
height: 100px;
background-color: black;
transition: width 0.3s, height 0.3s;
}
#blackbox:hover {
width: 200px;
height: 200px;
}
#blacktxt {
color: white;
text-align: center;
font-weight: bold;
margin-top: 10px;
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="blackbox"></div>
<div id="blacktxt">Navigation</div>
</body>
</html>