uni-app动态设置class

本文介绍了在uni-app中如何动态地为元素设置class,通过示例代码展示了具体实现过程,并给出了在Chrome浏览器中的运行效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

代码如下:

<template>
	<view class="body">
		<view class="body_box">
			<!--class操作-->
			<!--第一种方法-->
			<view class="border_title">标签class判断</view>
			<view class="eve_box">
				<view :class="index==0?'border_box green_box':'border_box yellow_box'"></view>
				<view :class="{'border_box':index==0,'green_box':index==1,'yellow_box':index==0}"></view>
			</view>
			<!--第二种方法-->
			<view class="border_title">方法class判断</view>
			<view class="eve_box">
				<view :class="[returnclass(0)]"></view>
				<view :class="[returnclass(1)]"></view>
			</view>
			<!--style操作-->
			<!--第一种方法-->
			<view class="border_title">标签style判断</view>
			<view class="eve_box">
				<view
					:style="{width:width+'rpx',height:height+'rpx',backgroundColor:index==0?'green':'yellow',border:`${border}rpx solid #333333`,borderRadius:radius+'rpx'}">
				</view>
				<view
					:style="{width:width+'rpx',height:height+'rpx',backgroundColor:index==1?'green':'yellow',border:`${border}rpx solid #333333`,borderRadius:radius+'rpx'}">
				</view>
			</view>
			<!--第二种方法-->
			<view class="border_title">方法style判断</view>
			<view class="eve_box">
				<view :style="returnstyle(0)"></view>
				<view :style="returnstyle(1)"></view>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				index: 0,
				height: 150,
				width: 150,
				border: 2,
				radius: 75
			}
		},
		onLoad() {

		},
		methods: {
			returnclass(index) {
				if (index == 0) {
					return "border_box green_box"
				} else if (index == 1) {
					return "border_box yellow_box"
				}
			},
			returnstyle(index) {
				let width = `width:${this.width}rpx;`
				let height = `height:${this.height}rpx;`
				let border = `border:${this.border}rpx solid #333333;`
				let radius = `borderRadius:${this.radius}rpx;`
				let selectcolor = index == 0 ? "green" : "yellow"
				let color = `backgroundColor:${selectcolor};`
				return `${width}${height}${border}${radius}${color}`
			}
		}
	}
</script>

<style lang="scss" scoped>
	.body {
		width: 750rpx;

		.body_box {
			padding: 30rpx 0;

			.eve_box {
				display: flex;
				flex-direction: row;
				align-items: center;
				justify-content: space-evenly;

				.green_box {
					background-color: green;
				}

				.yellow_box {
					background-color: yellow;
				}

				.border_box {
					width: 150rpx;
					height: 150rpx;
					border-radius: 75rpx;
					border: 2rpx solid #333333;
				}
			}

			.border_title {
				padding: 20rpx;
				font-size: 28rpx;
				font-weight: bold;
				text-align: center;
			}
		}
	}
</style>

Chrome运行效果如下:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值