如何在滾動時更改背景
學習如何使用 CSS 在滾動時更改背景圖像。
在滾動時更改背景圖像
請在框架內向下滾動,以查看效果:
如何在滾動時更改背景圖像
第一步 - 添加 HTML:
<div class="bg-image img1"></div> <div class="bg-image img2"></div> <div class="bg-image img3"></div> <div class="bg-image img4"></div> <div class="bg-image img5"></div> <div class="bg-image img6"></div> <div class="bg-text">TEXT</div>
第二步 - 添加 CSS:
body, html { height: 100%; margin: 0; font-family: Arial, Helvetica, sans-serif; } * { box-sizing: border-box; } .bg-image { /* 全高 */ height: 50%; /* 將圖像居中并適當地縮放 */ background-position: center; background-repeat: no-repeat; background-size: cover; } /* 所用的圖像 */ .img1 { background-image: url("img_snow.jpg"); } .img2 { background-image: url("img_girl.jpg"); } .img3 { background-image: url("img_lights.jpg"); } .img4 { background-image: url("img_nature.jpg"); } .img5 { background-image: url("img_forest.jpg"); } .img6 { background-image: url("img_woods.jpg"); } /* 將文本放置在頁面/圖像的中間 */ .bg-text { background-color: rgb(0,0,0); /* 回退顏色 */ background-color: rgba(0,0,0, 0.4); /* 黑色半透明 */ color: white; font-weight: bold; font-size: 80px; border: 10px solid #f1f1f1; position: fixed; /* 保持固定 */ top: 50%; left: 50%; transform: translate(-50%, -50%); z-index: 2; width: 300px; padding: 20px; text-align: center; }