javascript - 使用两个背景图像并动态修改不透明度
问题描述
我正在加载两个固定的主体背景图像,都设置为覆盖。滚动的页面下方有文本延伸;以及顶部和底部的导航图标。正如预期的那样,第二个背景覆盖了第一个,它看起来像一个正常的、单一加载的背景。
在从之前的问题中获取提示时,我使用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>
解决方案
我建议使用 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>
推荐阅读
- python - 二进制到十进制 Python 解决方案的字符串索引错误
- c++ - 使用 SQLAPI 库 (C++) 对“...”的未定义引用
- docker - docker compose in bitbucket - 无法连接到 unix:///var/run/docker.sock 上的 Docker 守护程序。docker 守护进程是否正在运行?
- xslt - 使用命名空间进行 xslt 转换后,输出中不再有标签
- php - Nextcloud API 递归获取文件/文件夹
- python - 如何使用 huggingface 或 spacy 或任何基于 python 的工作流将单词转换为数字
- windows - GitHub 有 3 个存储库。我需要将这些作为新回购的子文件夹,每个回购的历史都完好无损
- excel - 文本框数据到选定单元格的 Excel VBA 代码
- amazon-iam - 如何将 AWS SageMaker 提供给组织外部的人员使用?
- android - 如何在 android 中将 2021-07-06T19:27:46.811+0530 格式转换为 d MMM yyyy, hh:mm aaa 这种格式