vue 前端实现随机背景色

前言:

要求是页面对应的几个模块每次打开都要显示多个不同的随机颜色,点击刷新则显示的颜色改变。我就封装成了一个函数,有不足的地方,还希望多多指点。代码如下。


步骤:

  1. 封装一个函数
  2. 使用 for 循环,需要使用多少个背景色,就循环几次
  3. 使用 **Math.floor()**下舍入,把获取到的值进行取整
  4. 使用 Math.random() 方法获取随机数
  5. toString(16) 转换为 16 进制
  6. 点击刷新则重新调用封装的函数
  7. 点击颜色块则把颜色赋值到 input 框中
  8. 背景色页随之改变

功能效果展示:

在这里插入图片描述

vue 实现随机背景色


代码:

此代码包含所需要的所有功能,本文中使用了 element-ui 框架,部分代码功能可以进入官网进行查找,除了部分代码其他全部使用 vue 完成。

点击跳转至 element-ui 官方文档:https://element.eleme.cn/#/zh-CN/component/installation

<template>
  <div class="box">
    <el-input v-model="input" placeholder="请输入内容"></el-input>
    <div class="top">
      <div
        class="boxlist"
        v-for="(item, index) in lists"
        :key="index"
        v-bind:style="{
          backgroundColor: item,
        }"
        @click="addcolor(item)"
      >
        <p>{
   
   { item }}</p>
      </div>
    </div>
    <el-button type="primary" @click="add">主要按钮</el-button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      Number: "",
      lists: [],
      input: "",
    };
  },
  mounted() {
    // 进入时调用
    this.randoms();
  },
  methods: {
    randoms() {
      // 循环
      for (var i = 0; i < 24; i++) {
        // 把获取到的值赋值给 Number
        this.Number =
          "#" +
          // 下舍入(0-1随机数 乘以 255)转换为16进制
          Math.floor(Math.random() * 255).toString(16) +
          Math.floor(Math.random() * 255).toString(16) +
          Math.floor(Math.random() * 255).toString(16);
        // 追加到 lists 中
        this.lists.push(this.Number);
      }
    },
    add() {
      // 点击清空 lists
      this.lists = [];
      // 调用封装函数
      this.randoms();
    },
    addcolor(item) {
      // 颜色在 input 框中显示
      this.input = item;
      // 背景色改变
      this.$refs.top.style.backgroundColor = item;
    },
  },
};
</script>

<style lang="scss" scoped>
.box {
  background-color: rgb(196, 191, 191);
  .top {
    display: flex;
    flex-wrap: wrap;
    .boxlist {
      width: 150px;
      height: 150px;
      margin: 25px;
      p {
        width: 100%;
        height: 30px;
        background-color: #fff;
        line-height: 30px;
      }
    }
  }
}
</style>

总结:

以上就是 vue 中实现随机背景色的方法,不懂得也可以在评论区里问我或私聊我询问,以后会持续发布一些新的功能,敬请关注。
我的其他文章:https://blog.csdn.net/weixin_62897746?type=blog

猜你喜欢

转载自blog.csdn.net/weixin_62897746/article/details/128278201