纯CSS实现的幻灯片仅显示无序列表不展示背景壁纸如何解决
CSS幻灯片无法正常显示问题修复
原始代码
HTML代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>My Slideshow doesnt work :/</title> <link rel = "stylesheet" type="text/css" href = "/index.css"> </head> <body id = "page"> <ul class = "slideshow"> <li><span>Image 1</span></li> <li><span>Image 2</span></li> <li><span>Image 3</span></li> <li><span>Image 4</span></li> <li><span>Image 5</span></li> <li><span>Image 6</span></li> <li><span>Image 7</span></li> <li><span>Image 8</span></li> <li><span>Image 9</span></li> <li><span>Image 10</span></li> </ul> </body> </html>
CSS代码
.slideshow, .slideshow.slideshow{ position: fixed; width: 100%; height: 100%; top: 0px; left: 0px; z-index: 0; } .slideshow:after{ content: ''; background: transparent url(/img/pattern.png) repeat top left; } .slideshow li span{ width: 100%; height: 100%; position: absolute; top: 0px; left: 0px; color: transparent; background-size: cover; background-position: 50% 50%; background-repeat: none; opacity: 0; z-index: 0; animation: imageAnimation 72s linear infinite 0s; } .slideshow li:nth-child(1) span{ background-image: url(./img/img1.jpg); } .slideshow li:nth-child(2) span{ background-image: url(/img/img2.jpg); animation-delay: 12s; } .slideshow li:nth-child(3) span{ background-image: url(/img/img3.jpg); animation-delay: 24s; } .slideshow li:nth-child(4) span{ background-image: url(/img/img4.jpg); animation-delay: 36s; } .slideshow li:nth-child(5) span{ background-image: url(/img/img5.jpg); animation-delay: 48s; } .slideshow li:nth-child(6) span{ background-image: url(/img/img6.jpg); animation-delay: 60s; } .slideshow li:nth-child(7) span{ background-image: url(/img/img7.jpg); animation-delay: 72s; } .slideshow li:nth-child(8) span{ background-image: url(/img/img8.jpg); animation-delay: 84s; } .slideshow li:nth-child(9) span{ background-image: url(/img/img9.jpg); animation-delay: 96s; } .slideshow li:nth-child(10) span{ background-image: url(/img/img10.jpg); animation-delay: 108s; } @keyframes imageAnimation { 0% { opacity: 0; animation-timing-function: ease-in; } 8% { opacity: 1; animation-timing-function: ease-out; } 17% { opacity: 1 } 25% { opacity: 0 } 100% { opacity: 0 } } .no-cssanimations .slideshow li span{ opacity: 1; }
修复方案
- 重置列表默认样式:新增
.slideshow, .slideshow li { margin: 0; padding: 0; list-style: none; },清除ul、li默认的内外边距和列表圆点标记 - 补全伪元素属性:给
.slideshow:after添加position: absolute; width: 100%; height: 100%; top: 0; left: 0; z-index: 1;属性,确保纹理遮罩层正常显示 - 修正背景属性错误:将
background-repeat: none改为合法属性值background-repeat: no-repeat - 统一资源路径:将首图的相对路径
./img/img1.jpg和其余图片的根路径/img/xxx.jpg统一,避免部署路径变化导致的图片加载失败 - 调整动画参数:总动画时长为72s,第7张及之后的图片延迟超过总时长,会导致第一轮动画前72s无对应图片展示,可将动画总时长调整为120s,或调整后续图片的延迟时间,也可给第一张图片的span单独设置
opacity: 1避免首屏空白
内容的提问来源于stack exchange,提问作者Jan
相关产品推荐
相关产品推荐

