[英]How to preload full page background image without it flickering?
我正在嘗試加載一個簡單的網頁,該網頁的圖像覆蓋整個頁面背景。 但是,當第一次加載頁面時,在加載圖像時會出現明顯的白色閃爍一瞬間。 我已經嘗試過諸如但沒有效果的建議。 下面是我的代碼:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body, html {
height: 100%;
margin: 0;
}
.bg {
/* The image used */
background-image: url("img_girl.jpg");
/* Full height */
height: 100%;
/* Center and scale the image nicely */
background-position: center;
background-repeat: no-repeat;
background-size: cover;
}
</style>
</head>
<body>
<div class="bg"></div>
</body>
</html>
有沒有人有解決閃爍效果的方法?
如果你想要一個覆蓋整個頁面背景的圖像,你應該直接為<body>
元素設置它,如下所示:
body {
background-image: url(your_url/your_image.png);
background-position: center; // to center the image
background-repeat: no-repeat; // to not repeat the image
background-size: cover; // to cover the element
background-color: #000; // fallback if the image is not available
}
或使用 CSS 簡寫更緊湊:
background: #000 url(your_url/your_image.png) no-repeat center;
background-size: cover;
您可以將.bg設置為opacity 0 ,然后在頁面加載完成后使用 jQuery 添加一個 class 設置為opacity 1 。
如果您想要“淡入淡出”效果,只需添加一個過渡。
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style>
body, html {
height: 100%;
margin: 0;
}
.bg {
/* The image used */
background-image: url("img_girl.jpg");
/* Full height */
height: 100%;
/* Center and scale the image nicely */
background-position: center;
background-repeat: no-repeat;
background-size: cover;
transition: opacity 1.3s ease-out;
opacity: 0;
}
.bg.visible{
opacity: 1;
}
</style>
</head>
<body>
<div class="bg"></div>
</body>
<script type="text/javascript">
$(document).ready(function(){
$(window).on("load",function(){
$('.bg').addClass('visible');
});
});
</script>
</html>
也許不是最好的解決方案,但它對我有用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.