【vue】通过变量动态修改标签样式(特别是颜色)

1.效果图

【vue】通过变量动态修改标签样式(特别是颜色)_第1张图片

2.问题说明

1.应用场景:通过动态选择界面上的样式属性,例如字体大小、字体、是否加粗以及颜色,从而改变界面上的展示效果
2.有的表单内的样式可能无法覆盖或者没法改变
3.当变量改变后,css样式中也发生改变的效果

3.代码示例

<template>
  <div id="app">
    <div class="div" :style="{'--fontColor': setting.fontColor, '--fontFamily': setting.fontFamily, '--fontSize': setting.fontSize, '--fontWeight': setting.fontWeight}">
      <span>你好</span>
    </div>
    <div>
      <el-form label-position="left" label-width="70px" size="small">
        <el-form-item label="字体选择">
          <el-select v-model="setting.fontFamily" placeholder="请选择字体">
            <el-option label="宋体" value="宋体"></el-option>
            <el-option label="黑体" value="黑体"></el-option>
            <el-option label="微软雅黑" value="Microsoft YaHei"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="字体大小">
          <el-select
            v-model="setting.fontSize"
            placeholder="请选择字体大小"
          >
            <el-option label="14px" value="14px"></el-option>
            <el-option label="16px" value="16px"></el-option>
            <el-option label="18px" value="18px"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="字体加粗">
          <el-button type="text" v-if="setting.fontWeight!='bold'"  @click="setFontWeight">加粗</el-button>
          <el-button type="text" v-if="setting.fontWeight=='bold'" @click="setFontWeight">不加粗</el-button>
        </el-form-item>
        <el-form-item label="字体颜色">
          <el-color-picker
            v-model="setting.fontColor"
          ></el-color-picker>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
export default {
  name: "app",
  data() {
    return {
      setting: {
        fontFamily: "宋体",
        fontSize: "14px",
        fontWeight: "bold",
        fontColor: "#597cf0",
      }
    };
  },
  methods: {
    setFontWeight() {
      this.setting.fontWeight = this.setting.fontWeight == "bold" ? "normal" : "bold";
    }
  },
};
</script>
<style lang="scss">
  .div span{
    color: var(--fontColor) !important;
    font-family: var(--fontFamily) !important;
    font-size: var(--fontSize) !important;
    font-weight: var(--fontWeight) !important;
  }
</style>

你可能感兴趣的:(vue,css,css,javascript,html)