在不影响文本的情况下更改 CSS 中的背景图像不透明度

参考文档

https://coder-coder.com/background-image-opacity/

问题描述

我们在搭建网站的过程中,希望将背景图片放到<div>并包含文本内容的HTML上,此时想要重点显示文本内容,便需要通过调试背景图片的透明度来达到目的,但是一般情况下,单纯的设置opacity,反而会使文本内容随着背景图片一起弱化,达不到想要的效果。如下述代码:

<view >
		<div class="iii">
			<!-- <view class="u-demo-title">演示效果</view> -->
				<view class="wrap" v-for="item in productLists.jobs" >
					<view class="demo-layout bg-purple">
						<u-button class="debug" @click="list1(item.url)"  type="primary" shape="square" :plain="true"  :ripple="true">{{ item.name }}</u-button>
					</view>	
			          </view>
		</div>

</view>
<style lang="scss" scoped>
	.iii {
		background-image: url("./slb_jpg.jpg");
		position: relative; 
		opacity: 0.6;
		// z-index: 1;
		background-size: cover;
	}
</style>

上述代码正常情况下,文本内容背景图片会随着opacity 的透明度一起变化,此时我们就需要其他途径来实现我们想要的需求

方案1

将背景图片放入父级的伪元素中。
这样可以确保背景图像和文本内容将在父级中各自的“层”上。可以控制每一层的不透明度,而不会相互影响。

<view >
		<div class="iii">
			<!-- <view class="u-demo-title">演示效果</view> -->
				<view class="wrap" v-for="item in productLists.jobs" >
					<view class="demo-layout bg-purple">
						<u-button class="debug" @click="list1(item.url)"  type="primary" shape="square" :plain="true"  :ripple="true">{{ item.name }}</u-button>
					</view>	
			          </view>
		</div>

</view>
<style lang="scss" scoped>
	.iii {
		position: relative; 
		background-size: contain;
	}
	.iii::before {
		background-image: url("./slb_jpg.jpg");
		background-size: cover;
		position: absolute;
		opacity: 0.4;
                // 必填项,下方有解释
		top: 0px;
		right: 0px;
		bottom: 0px;
		left: 0px;
                content: "";
	}
</style>

要使该伪元素与父元素大小相同,您必须绝对位置并将其顶部、右侧、底部和左侧的值设置为零,这样它就不会崩溃。另外,作为伪元素,它需要 content 设置属性,否则它不会显示在页面上。

方案2

在背景图像顶部添加降低不透明度和背景颜色的叠加层。
这一步,使用background-color: rgba(255, 255, 255, 0.9)的最后一个参数 0.9来实现

<view >
		<div class="iii">
			<!-- <view class="u-demo-title">演示效果</view> -->
				<view class="wrap" v-for="item in productLists.jobs" >
					<view class="demo-layout bg-purple">
						<u-button class="debug" @click="list1(item.url)"  type="primary" shape="square" :plain="true"  :ripple="true">{{ item.name }}</u-button>
					</view>	
			          </view>
		</div>

</view>
<style lang="scss" scoped>
	.iii {
                background-image: url("./slb_jpg.jpg");
		position: relative; 
		background-size: contain;
	}
	.iii::before {
		background-color: rgba(255, 255, 255, 0.9);
		background-size: cover;
		position: absolute;
		opacity: 0.4;
                // 必填项,下方有解释
		top: 0px;
		right: 0px;
		bottom: 0px;
		left: 0px;
                content: "";
	}
</style>

posted @ 2022-06-15 14:18  耿小耿的技术博客  阅读(613)  评论(0)    收藏  举报