带有背景图像 url 的 CSS 变量

新手上路,请多包涵

我是否误解了 CSS 变量的功能?我正在尝试将背景图片 url 传递给这样的变量:当我传递一些简单的东西(如颜色等)时,它似乎工作正常……

 :root {
  --slide-1: url(/static/images/slideshow/slide1.jpg) ;
  --slide-2: url(/static/images/slideshow/slide2.jpg) ;
  --slide-3: url(/static/images/slideshow/slide3.jpg) ;
  --slide-4: url(/static/images/slideshow/slide4.jpg) ;
  --slide-5: url(/static/images/slideshow/slide5.jpg) ;
}

//and then

.jumbotron > .jumbotron-slideshow:nth-child(1) {
  background-image: var(--slide-1);
}

.jumbotron > .jumbotron-slideshow:nth-child(2) {
  animation-delay: 6s;
  background-image: var(--slide-2);
}

.jumbotron > .jumbotron-slideshow:nth-child(3) {
  animation-delay: 12s;
  background-image: var(--slide-3);
}

.jumbotron > .jumbotron-slideshow:nth-child(4) {
  animation-delay: 18s;
  background-image: var(--slide-4);
}

.jumbotron > .jumbotron-slideshow:nth-child(5) {
  animation-delay: 24s;
  background-image: var(--slide-5);
}

原文由 Sandra Willford 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 2.1k
1 个回答

-- 简化版 –

使用 SCSS 帮助减少重复代码:

 @for $i from 1 through 5 {
  :root { --slide-#{$i}: url(/static/images/slideshow/slide#{$i}.jpg); }

  //and then

  .jumbotron > .jumbotron-slideshow:nth-child(#{$i}) {
    animation-delay: #{($i - 1) * 6}s;
    background-image: var(--slide-#{$i});
  }
}

原文由 allenski 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题