透明元素与背景附件的交互:已修复

  • 本文关键字:交互 元素 背景 透明 html css
  • 更新时间 :
  • 英文 :


为什么div"透明区域";没有显示固定的background-image?MDN表示;[…]背景图像的位置在视口[…]"内是固定的;,所以我确实认为网站的任何透明部分都会让背景再次可见。

<div id="background"></div>
<div id="first-section">A B C D E F</div>
<div id="transparent-area"></div>
<div id="second-section">G H I J K L</div>
#background {
height: 100vh;
background-image: url("https://images.unsplash.com/photo-1612225330812-01a9c6b355ec?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=2670&q=80");
background-size: cover;
background-attachment: fixed;
background-repeat: no-repeat;
}
#first-section {
height: 300px;
background-color: #000033;
}
#second-section {
height: 300px;
background-color: #000033;
}
#transparent-area {
height: 300px;
}

Fiddle:https://jsfiddle.net/t4sdpy6g/14/

问题是为什么透明div没有显示第一个div的背景。

答案是第一个div已经滚动出了视图。

第一个div尚未在视口中固定。只有它的背景已经固定好了——当div滚动到视图之外时,它不会"落后"。

如果移除其他div,但将第一个放入一个非常高的div中并滚动,则可以看到这一点。

如果你使用IOS15之前的Safari版本,你也可以看到它——这些版本不支持背景附件,背景开始立即滚动出视图。

如果你想要的是一种视差效果,在这种效果中,bacground图像保持固定,而其他人则在其上滚动,那么按照@alejskorovin的答案,将第一个div作为其他div的包装。

您可以稍微更改标记和样式,并将#background作为带有填充100vh的包装器。请检查下面的示例(https://codepen.io/alekskorovin/pen/zYEGxjd):

#background {
padding-top: 100vh;
background-image: url("https://images.unsplash.com/photo-1612225330812-01a9c6b355ec?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=2670&q=80");
background-size: cover;
background-attachment: fixed;
background-repeat: no-repeat;
}
#first-section {
height: 300px;
background-color: #000033;
}
#second-section {
height: 300px;
background-color: #000033;
}
#transparent-area {
height: 300px;
}
<div id="background">
<div id="first-section">A B C D E F</div>
<div id="transparent-area"></div>
<div id="second-section">G H I J K L</div>
</div>

最新更新