当我将鼠标悬停在链接上时,我想为我的 body 背景制作动画,有人可以帮我吗。
我有一个改变背景颜色的动画“myfirst”,
@keyframes myfirst
{
from{background: black;}
to{background: white;}
}
@-webkit-keyframes myfirst /* Safari and Chrome */
{
from{ background: black;}
to{background: white;}
}
现在我已经做到了,当我将鼠标悬停在 body 上时会触发动画。
body:hover{
animation: myfirst 0.01s;
animation-iteration-count:500;
-webkit-animation: myfirst 0.01s;
-webkit-animation-iteration-count:500;
}
我想要一个链接触发改变我的 body 背景的动画。
最佳答案
正如其他人所说,为了在单击元素时更改 body
,您需要有一个父选择器。由于 CSS 没有父选择器功能,您将不得不使用一些 javascript
// Set onclick function for the element you want
document.getElementById('changeBG').onmouseover = function() {
document.body.style.animation = "myfirst 0.01s 500"; //Give the body the anim
// The above could also be done by adding a class with the animation
// properties on click
};
但是,如果您只想在链接悬停时背景闪烁,否则停止,您可以使用另一个 HTML 元素(一种伪造的 body
)在纯 CSS 中实现。它要求 fake-body 元素像这样跟随文档流中的链接
<a id='changeBG' href='#'>Change background</a>
<div id='cover'></div>
以及该假体元素的 CSS
#cover {
position:absolute; /* Don't affect other elements */
top:0; left:0; /* Fill up the entire viewport */
width:100%;
height:100%;
z-index:-1; /* Be placed behind all other elements */
}
然后您将使用兄弟选择器(我使用 +
直接跟随兄弟)和 :hover
将动画提供给假体
#changeBG:hover + #cover {
-webkit-animation: myfirst 0.01s 500;
animation: myfirst 0.01s 500;
}
关于javascript - 如何从触发器 x 触发 y 元素的 css 动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20101729/