如何为悬停的背景图像修复CSS过渡?

时间:2019-04-05 17:47:18

标签: css html5 css-transitions navbar

我正在一个School项目中创建一个电子商务网站,我想在navbar块(ul内的lis)上进行CSS转换,就像当我将鼠标悬停在一个块上时,该块的背景图像显示向上,但似乎过渡不起作用,仅发生正常的即时悬停。

这是我的代码,仅显示导航栏的一个块,即目录

#catalogue {
  -o-transition-property: all;
  -o-transition-duration: 2s;
  -o-transition-timing-function: ease-in-out;
  -o-transition-delay: 2s;
  background-size: cover;
  background-repeat: no-repeat;
}

#catalogue:hover {
  display: inline-block;
  margin-left: 70px;
  position: relative;
  background-image: url(f1.png);
  background-size: 125px 70px;
  color: #000;
  font-weight: 600;
}
<nav>
  <ul>
    <li id="home"><a>Home</a></li>
    <li id="catalogue"><a>Catalogue</a></li>
    <li id="news"><a>News&Trends </a></li>
    <li id="contact"><a>Contact us</a></li>
  </ul>

2 个答案:

答案 0 :(得分:2)

您不需要在过渡属性上使用歌剧(-o-)前缀。 CSS过渡不再需要前缀:http://shouldiprefix.com/#transitions

对于背景效果,应该使用CSS动画代替过渡效果,因为从今天起,无法将过渡效果应用于背景属性。

li {
  transition: all 2s ease-in-out 2s;
  background-size: cover;
  background-repeat: no-repeat;
}

li:hover {
  margin-left: 70px;
  position: relative;
  background-size: 125px 70px;
  color: #000;
  font-weight: 600;
  animation: backgroundIMG 2s ease-in-out 2s;
  animation-fill-mode: forwards;
}

@keyframes backgroundIMG {
  100% { background-image: url(http://www.rayesdesign.com/glitters/blue/blue016.gif); }
}

看到它在这里运行:https://jsfiddle.net/Lkawnpg6/1/

Ps。我已更改图像进行测试。

答案 1 :(得分:1)

您不能像这样转换背景图像。

您可以尝试在背景的顶部添加一个额外的div(或伪元素:before或:after),然后过渡其不透明度。

通常,您会像下面那样过渡背景颜色

.box {
  display: block;
  width: 100px;
  height: 100px;
  background-color: green;
  transition: background-color 0.3s ease;
}

.box:hover {
  background-color: red;
}
<div class="box"></div>

相关问题