JS控制CSS

121 阅读1分钟

使用场景

很多时候我们希望某DOM的CSS是动态的变化的,根据传参或者行为的不同产生不同的CSS样式,本文记录一些实际使用场景以供参考。

页面加载时根据传参的不同加载不同的CSS

页面加载时,由于前页面传参的不同,而需要有不同的CSS样式,例如从商务和普通入口分别进入页面,希望页面的背景图片、按钮颜色是不一样的

<view class="container" :class="bkgType">

</view>
data() {
    return {
	type: '',
	bkgType:'',
	orderType: '',
	manageType: '',
	stockType: '',
    }
},
onLoad(options) {
this.type = options.type;
this.bkgType = options.type === '1' ? 'bkg-business' : 'bkg-normal';
},
.container {
		width: 100vw;
		min-height: 100vh;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}
	
	.bkg-business {
		background: url('@/static/image/business.jpg');
		background-position: right top;
		background-repeat: no-repeat;
		background-attachment: fixed;
		background-size: cover;
		position: relative;
		overflow: hidden;
	}
	
	.bkg-normal {
		background: url('@/static/image/normal.jpg');
		background-position: right top;
		background-repeat: no-repeat;
		background-attachment: fixed;
		background-size: cover;
		position: relative;
		overflow: hidden;
	}

这里view标签绑定了两个class,一个是container基础固定样式,一个是动态绑定样式bkgType,bkgType默认为空,在页面加载时,通过传参的值的不同来给bkgType赋不同的值,代码中bkg-business、bkg-normal都是CSS的类名,从而实现CSS样式切换。

点击之后触发不同样式

类似选项卡效果,选中的标签会触发选中样式,未选中的则不会有样式

<view v-for="(category, index) in categories" :key="index"
:class="['category-item', currentCategory === index ? 'active' : '']" @click="selectCategory(index)">
{{ category.name }}
</view>
// 选择分类
selectCategory(index) {
    this.currentCategory = index
},
	.category-item {
		padding: 30rpx 20rpx;
		text-align: center;
		border-bottom: 1px solid #EEEEEE;
		color: var(--gray-medium);
		position: relative;
		transition: all 0.3s ease;
		font-size: 36rpx;
	}

	/* 分类选中状态样式 */
	.category-item.active {
		background-color: var(--primary-light);
		/* color: var(--primary-color); */
		font-weight: bold;
	}