style属性绑定(样式较少时) + 随机颜色生成+class属性绑定(样式较多时)

1.style属性绑定

通过v-bind进行属性绑定,引号里面是js语法,因为style属性值是 键值对的形式,所以我们这里用对象的形式来表示。(Vue2中)

<template>
	<view>
		<view class="box" :style="{backgroundColor:randomcolor}" @click="randomColor">点击一下颜色随机变化</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				randomcolor:'pink',
			}	
		},
		methods:{
			randomColor(){
				let arr = ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'];
				let randomStrArr = [];
				for(let i=0;i<=5;i++){
					randomStrArr[i] = arr[Math.floor(Math.random()*arr.length)];
				}
				this.randomcolor = `#${randomStrArr.join("")}`;
			}
			// randomColor(){
			// 	let r = Math.floor(Math.random()*256);
			// 	let g = Math.floor(Math.random()*256);
			// 	let b = Math.floor(Math.random()*256);
			// 	this.randomcolor = `rgb(${r},${g},${b})`
			// }
		}
	}
</script>

<style lang="scss">
	.box{
		width: 200rpx;
		height: 200rpx;
	}
</style>

2.随机颜色生成

01.十六进制的方式

            randomColor(){
				let arr = ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'];
				let randomStrArr = [];
				for(let i=0;i<=5;i++){
					randomStrArr[i] = arr[Math.floor(Math.random()*arr.length)];
				}
				this.randomcolor = `#${randomStrArr.join("")}`;
			}

02.rgb的形式

            randomColor(){
				let r = Math.floor(Math.random()*256);
				let g = Math.floor(Math.random()*256);
				let b = Math.floor(Math.random()*256);
				this.randomcolor = `rgb(${r},${g},${b})`
			}

3.class属性绑定

<template>
	<view>
		<!-- <view class="block" :class="{myactive:state}" @click="changeBgc">点我就变</view> -->
		<view class="block" :class="state ? 'myactive':''" @click="changeBgc">点我就变</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				state:true,
			}	
		},
		methods:{
			changeBgc(){
				this.state = !this.state;
			}
		}
	}
</script>

<style lang="scss">
	.block{
		width: 200rpx;
		height: 200rpx;
		background-color: #ccc;
	}
	.myactive{
		width: 400rpx;
		height: 400rpx;
		background-color: pink;
		border-radius: 5%;
	}
</style>

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值