Skip to content

背景图片渐入

背景图片一般最后加载,先加载图片可能会导致主页打开慢的情况。 先加载主体容器后加载图片分两种情况: 1.主体容器加载背景图片,那么后背景图片加载主体会闪一下。这个用动画也是过渡不了的。 2.主体容器与背景图为兄弟关系,那么主体要用绝对定位等方式覆盖在背景图上层

dom 结构

<div>
<div class="bg-image"></div>
<div class="main-container">
/** main content**/
<div></div>
</div>
</div>

css样式

//主体容器背景用css
.main-container{
background-color:rgba(255,255,255,0)
}
//背景图容器css
#bg-image{
width: 100%;
height: 100%;
overflow: hidden;
position:absolute;
top:0;
left:0;
background-size: cover;
background-position: 50% 50%;
background-repeat: no-repeat;
//opacity animation
opacity:0;
animation-delay: 0s;
animation-duration: 1s;
animation-fill-mode: forwards;
animation-timing-function: ease-in;
}
//关键帧动画
@keyframes load {
0% { opacity: 0; }
100% { opacity: 1; }
}

延时加载图片

//create image
const domImage = new Image()
domImage.src = "https://cn.bing.com/ImageResolution.aspx?w=375&h=812&hash=4c53f273ecb43b0f5ed8318a5684a324"
//create image load event
domImage.onLoad = ()=>{
let bg = document.querySelector("#bg-image")
bg.style = `
background-image:url(${background.src});
animation-name: load;
`
}