CSS3过渡缓动进出盒阴影

37

我正在试图使用CSS3使div id在盒子阴影中缓慢出现和消失。

我当前的CSS是:

#how-to-content-wrap-first:hover {
    -moz-box-shadow: 0px 0px 5px #1e1e1e; 
    -webkit-box-shadow: 0px 0px 5px #1e1e1e; 
    box-shadow: 0px 0px 5px #1e1e1e;
    -webkit-transition: box-shadow 0.3s ease-in-out 0s;
    -moz-transition: box-shadow 0.3s ease-in-out 0s;
    -o-transition: box-shadow 0.3s ease-in-out 0s;
    -ms-transition: box-shadow 0.3s ease-in-out 0s;
    transition: box-shadow 0.3s ease-in-out 0s;
}

我遇到的问题是,当第一次将鼠标悬停在元素上时,没有缓入或缓出效果,然后任何后续的悬停都会缓入但不会缓出。

有什么建议吗?非常感谢大家!

3个回答

71

你需要在 .class 上使用过渡效果,而不是 .class:hover

div {
  height: 200px;
  width: 200px;
  box-shadow: 0;
  transition: box-shadow 1s;
  border: 1px solid #eee;
}

div:hover {
  box-shadow: 0 0 3px #515151;
  ;
}
<div></div>


7
在 div 中,需要将 box-shadow: none 设置为无阴影。 - Karl Glaser
2
有一种更好(=性能优化)的方法来实现盒子阴影动画。请参见http://tobiasahlin.com/blog/how-to-animate-box-shadow/ - Pointi

4

这里有一个资源高效的解决方案

#how-to-content-wrap-first::after{
    /* Pre-render the bigger shadow, but hide it */
    box-shadow: 3px 3px 5px -1px #80aaaa;
    opacity: 0;
    transition: opacity 0.3s ease-in-out;         
}

#how-to-content-wrap-first:hover::after {
    /* Transition to showing the bigger shadow on hover */
    opacity: 1;
}

2
这可能有效:

 #how-to-content-wrap-first:hover{
      box-shadow : inset 0 1px 1px rgba(0,0,0,.075);
      -webkit-transition : box-shadow ease-in-out .15s;
      transition : box-shadow ease-in-out .15s;
 }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接