<分区>
标签 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/