我正在加载两个固定的主体背景图像,都设置为覆盖。在滚动页面下方延伸的文字;以及顶部和底部导航图标。不出所料,第二个背景覆盖了第一个背景,看起来像是普通的单个加载背景。
在从以前的问题中获取提示时,我将body {}
用于第一个(现已隐藏)背景图像,并将body:after {}
用于第二个(在顶部,可见和不透明度可调的)背景图像-图片。
我可以使用CSS body:after {opacity:.5}
(或任何其他值0-> 1)来获得顶部背景图像的单个所需效果,同时使文本和导航图标保持完全不透明。但是,我无法访问不透明度值来更改它。一旦我能够在知识渊博的人的帮助下这样做,我就应该能够向前移动以动态增加值的交换,从1->。9->。8-> etc .-> 0消失顶部背景图片使用带有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>
答案 0 :(得分:2)
我建议使用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>