插件窝 干货文章 Vue项目中如何动态改变el-input组件选中时的背景颜色?

Vue项目中如何动态改变el-input组件选中时的背景颜色?

input activeBgColor 样式 style 173    来源:    2025-03-26

Vue项目中动态改变el-input组件选中时的背景颜色

在Element UI的Vue项目中,要动态改变el-input组件选中时的背景颜色,可以通过以下几种方法实现:

方法一:使用CSS伪类选择器

/* 全局样式或在组件样式中 */
.el-input__inner:focus {
  background-color: your-dynamic-color !important;
  border-color: your-border-color !important;
}

然后在Vue组件中动态绑定样式:

<template>
  <el-input 
    :style="{'--input-focus-bg': activeBgColor}"
    v-model="inputValue"
  ></el-input>
</template>

<script>
export default {
  data() {
    return {
      inputValue: '',
      activeBgColor: '#f0f9eb' // 默认颜色
    }
  },
  methods: {
    changeBgColor(newColor) {
      this.activeBgColor = newColor;
    }
  }
}
</script>

<style>
.el-input__inner:focus {
  background-color: var(--input-focus-bg) !important;
}
</style>

方法二:使用动态类名

<template>
  <el-input 
    :class="{'custom-focus': isActive}"
    v-model="inputValue"
    @focus="isActive = true"
    @blur="isActive = false"
  ></el-input>
</template>

<script>
export default {
  data() {
    return {
      inputValue: '',
      isActive: false,
      activeBgColor: '#f0f9eb'
    }
  },
  methods: {
    changeBgColor(newColor) {
      this.activeBgColor = newColor;
    }
  }
}
</script>

<style>
.custom-focus .el-input__inner:focus {
  background-color: v-bind(activeBgColor) !important;
}
</style>

方法三:使用深度选择器(适用于scoped样式)

<template>
  <el-input 
    ref="myInput"
    v-model="inputValue"
  ></el-input>
</template>

<script>
export default {
  data() {
    return {
      inputValue: '',
      activeBgColor: '#f0f9eb'
    }
  },
  mounted() {
    this.updateInputStyle();
  },
  methods: {
    changeBgColor(newColor) {
      this.activeBgColor = newColor;
      this.updateInputStyle();
    },
    updateInputStyle() {
      const style = document.createElement('style');
      style.innerHTML = `
        .el-input__inner:focus {
          background-color: ${this.activeBgColor} !important;
        }
      `;
      // 移除旧样式
      const oldStyle = document.getElementById('dynamic-input-style');
      if (oldStyle) oldStyle.remove();

      // 添加新样式
      style.id = 'dynamic-input-style';
      document.head.appendChild(style);
    }
  }
}
</script>

注意事项

  1. 使用!important是为了覆盖Element UI的默认样式
  2. 在scoped样式中,需要使用深度选择器::v-deep/deep/(取决于Vue版本)
  3. 动态改变颜色时,考虑添加过渡效果提升用户体验:
.el-input__inner {
  transition: background-color 0.3s ease;
}

以上方法可以根据项目需求选择使用,方法一和方法二更为简洁,方法三适用于需要更复杂动态样式控制的场景。