javascript - 使用两个背景图像并动态修改不透明度

标签 javascript html css

<分区>

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

根据前面问题的提示,我使用 body {} 作为第一个(现在隐藏的)背景图像,使用 body:after {} 作为第二个(在顶部,可见和不透明度可调)背景图像。

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

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

(附言:使用@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>

最佳答案

我建议使用 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>

关于javascript - 使用两个背景图像并动态修改不透明度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59150029/

上一篇:html - 如何制作完整部分的 youtube 视频背景封面

下一篇:html - 如何创建 3 列嵌套 CSS 网格布局?

相关文章:

javascript - 如何将多个 d3 图表导出到 powerpoint?

php - Img 源字符串未正确连接对象变量

javascript - 这个 jquery 下拉菜单有什么问题

javascript - 仅调用数组中的最后一个对象,async.each 或eachSeries 不起作用

javascript - jQuery - 从 HTML 字符串中,找到具有给定数据属性的所有元素

html - 尝试使用 sass/css 在第二行之后添加省略号?

html - 为什么我的填充仅在元素处于悬停状态时显示?

css - PrimeNG 数据表条件单元格格式

asp.net - 如何将母版页和CSS应用于子页

javascript - 从桌面应用程序连接到 AWS MySQL 数据库