gpt4 book ai didi

javascript - 使用 GetElementById 时更改图像不透明度

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:12:40 28 4
gpt4 key购买 nike

我的 Uni 模块的一部分要求我制作一个使用随机元素混合故事的网络故事。我在 JS 中使用 GetElementById 将一个随机图像从一个数组嵌入到一个 div 中,效果非常好。该图像成为 div 的背景,然后我在图像顶部添加了文本 - 同样,这一切都完美无缺。

但是问题是我希望图像稍微透明以便文本更易于阅读,但是无论我尝试什么解决方案,我都无法让它工作。

我已经尝试在 CSS 和 JS 中使 div 透明,但是随后整个 div(包括文本)都会受到影响,这就违背了这一点。然后当我在 CSS 中尝试 RGBA 样式时,图像不受影响。

所以我需要的是通过 JS 加载到 div 中的图像稍微透明,而同样在 HTML 文档中的 div 中的文本保持不变。

这是我用来随机选择图像的 JS:

function randomGun() {
var imgCount = 3;
var dir = 'img/';
var randomCount = Math.round(Math.random() * (imgCount - 1)) + 1;
var images = new Array
images[1] = "gun1.jpg",
images[2] = "gun2.jpg",
images[3] = "gun3.jpg",
document.getElementById("left").style.backgroundImage = "url(" + dir + images[randomCount] + ")";
}
<div id="container">
<div id="left">
<a id="message">Drive a bit closer to see if anybody is there.</a>
</div>

<script>
window.onload = randomGun()
</script>

</div>

最佳答案

使用半透明白色背景的嵌套 div。

<div id="container">
<div id="left">
<div id="nested" style="width:100%;height:100%; background-color: rgba(255,255,255,0.5)">
<a id="message">Drive a bit closer to see if anybody is there.</a>
</div>
</div>

<script>window.onload = randomGun()</script>

</div>

此外,我会在样式表中或至少在 <style></style> 中设置与样式相关的所有内容.

关于javascript - 使用 GetElementById 时更改图像不透明度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42159240/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com