首页 > 解决方案 > 使用两个背景图像并动态修改不透明度

问题描述

我正在加载两个固定的主体背景图像,都设置为覆盖。滚动的页面下方有文本延伸;以及顶部和底部的导航图标。正如预期的那样,第二个背景覆盖了第一个,它看起来像一个正常的、单一加载的背景。

在从之前的问题中获取提示时,我使用body {}了第一个(现在隐藏的)背景图像和body:after {}第二个(在顶部、可见和不透明度可调的)背景图像。

我可以使用CSS body:after {opacity:.5}(或任何其他值 0->1)来实现顶部背景图像的单一所需效果,同时保持我的文本和导航图标完全不透明。但是,我无法访问不透明度值来更改它。一旦我能够在更有知识的人的帮助下这样做,我就应该能够继续从 1->.9->.8->etc.->0 动态增加值的交换以消失顶部背景图像使用具有 11 帧和适当时间间隔的计时器。

下面是我成功的代码片段以及我在访问不透明度值时失败的 Javascript 尝试。

(PS:使用@RickardElimää 出色的终极答案,顶部背景开始是透明的,因此实际上最终成为淡入。)

body {
  background-image: url('./MyPhoto-1.jpg') ; 
  position: static; /* to work with Edge 10 */
  /* z-index: -2 ; */
  background-position: center center ; 
  background-repeat: no-repeat ; 
  background-attachment: fixed ; 
  background-size: cover ; 
}

body:after { 
  content: " ";
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  background-image: url('./MyPhoto-2.jpg') ; 
  position: fixed ; 
  z-index: -2 ; 
  background-position: center center ; 
  background-repeat: no-repeat ; 
  background-attachment: fixed ; 
  background-size: cover ; 
/* arbitrarily set immediately below and needing to be accessed via Javascript */
  opacity: .4 ;
}


<script>//PROBLEM with scripting access to above opacity value
  // document.body.getElementById("triedDivAndBodyTag").style.opacity = ".8"
  document.getElementByID("body:after").style.opacity="0.8";
</script>

标签: javascripthtmlcss

解决方案


我建议使用 CSS 变量,因为您(出于某种明显的原因)无法通过 JavaScript 访问 CSS 属性的值。此外,尽可能长时间地尝试使用 CSS 动画,因为它已针对它进行了更好的优化。

:root {
  --background-opacity: 0.4;
}

body {
  background-image: url('./MyPhoto-1.jpg') ; 
  position: static; /* to work with Edge 10 */
  /* z-index: -2 ; */
  background-position: center center ; 
  background-repeat: no-repeat ; 
  background-attachment: fixed ; 
  background-size: cover ; 
}

body:after { 
  content: " ";
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  background-image: url('./MyPhoto-2.jpg') ; 
  position: fixed ; 
  z-index: -2 ; 
  background-position: center center ; 
  background-repeat: no-repeat ; 
  background-attachment: fixed ; 
  background-size: cover ; 
  opacity: var(--background-opacity);
  transition: opacity 1100ms;
}

<script>
  document.documentElement.style.setProperty('--background-opacity', 0.8);
</script>

推荐阅读