使用 jquery 或 css 过渡属性在悬停 link 时将一张背景图片淡化为另一张背景图片

Fade one background image for another on hover of link using jquery or css transition properties

标题可能有点混乱。

我有 .main-container div 保存我的整个页面内容。

在 link 上悬停在 #cheffing 我需要将 .main-container 的背景图片从一张图片更改为另一张图片并在两张图片之间淡入淡出。

问题是,在淡入淡出期间,我希望 .main-container 中的内容仍然可见,只影响背景图像,而不影响整个容器。

我什至不确定如何解决这个问题。我应该只使用 jQuery 吗? CSS? classToggle()fadeOut()?我不确定...

我正在使用 jQuery。抱歉,如果这没有意义。如果您需要更多,我会在附近。

代码笔

https://codepen.io/JDSWebService/pen/NjmrRv

HTML

<div class=".main-container">
  Other Misc Page Content
  <a href="#" id="cheffing">Cheffing</a>
  Other Misc Page Content
</div>

CSS

.main-container {
  height: 100vh;
  background: url("../imgs/background.jpg");
  background-size: cover;
  background-position: 0 0;
  background-repeat: no-repeat;
  transition: background 1s ease-out;
}

您不能为背景制作动画。

这里是an simple example.

因此,将图像 元素 定位在您想要背景的元素中,因为 absolute 具有较低的 z-index 将使它落后于其余部分的内容。

然后使用.hover()可以在两个图像之间切换URL。


编辑
这是 second example 在 1 个图像上使用 2 个图像而不是 2 个 URL(以避免 之间的白色)。

HTML:

<div class=".main-container">
  <img id="background-1" src="firstImage.jpg">
  <img id="background-2" src="secondImage.jpg">
  content...

CSS:

.main-container {
  height: 100vh;
  background-size: cover;
  background-position: 0 0;
  background-repeat: no-repeat;
  transition: background 1s ease-out;
}
#background-1,#background-2{
  position:absolute;
  z-index:-1;
  width:100%;
  height:500px;
}
#background-2{
  display:none;
}

jQuery:

var fadeOptions = {
  duration:600,
  easing:"linear"
};

$("#cheffing").hover(function(){
  $("#background-1").fadeOut(fadeOptions);
  $("#background-2").fadeIn(fadeOptions);
},
function(){
  $("#background-2").fadeOut(fadeOptions);
  $("#background-1").fadeIn(fadeOptions);
});