插件窝 干货文章 Vue项目中如何动态修改Element-UI el-input输入框的选中状态背景色?

Vue项目中如何动态修改Element-UI el-input输入框的选中状态背景色?

selection color style input 740    来源:    2025-03-26

动态修改Element-UI el-input选中状态背景色

在Vue项目中动态修改Element-UI的el-input输入框选中状态(selection)的背景色,可以通过以下几种方式实现:

方法一:使用CSS自定义样式

/* 全局样式 */
.el-input__inner::selection {
  background-color: #ff0000; /* 红色背景 */
  color: #fff; /* 白色文字 */
}

/* 或者针对特定输入框 */
.custom-input .el-input__inner::selection {
  background-color: #00ff00; /* 绿色背景 */
}

然后在Vue组件中动态切换类名:

<template>
  <el-input 
    :class="{'custom-input': isCustomSelection}"
    v-model="inputValue"
  />
  <el-button @click="toggleSelectionColor">切换选中颜色</el-button>
</template>

<script>
export default {
  data() {
    return {
      inputValue: '',
      isCustomSelection: false
    }
  },
  methods: {
    toggleSelectionColor() {
      this.isCustomSelection = !this.isCustomSelection
    }
  }
}
</script>

方法二:使用内联样式(动态style)

<template>
  <el-input 
    :style="{'--selection-color': selectionColor}"
    v-model="inputValue"
  />
  <el-button @click="changeSelectionColor('#ff0')">改为黄色</el-button>
</template>

<script>
export default {
  data() {
    return {
      inputValue: '',
      selectionColor: '#f00' // 默认红色
    }
  },
  methods: {
    changeSelectionColor(color) {
      this.selectionColor = color
    }
  }
}
</script>

<style>
/* 使用CSS变量 */
.el-input__inner::selection {
  background-color: var(--selection-color, #409EFF); /* 默认使用Element主题色 */
}
</style>

方法三:使用JavaScript动态修改样式

<template>
  <el-input 
    ref="myInput"
    v-model="inputValue"
  />
  <el-button @click="setSelectionColor('#00f')">改为蓝色</el-button>
</template>

<script>
export default {
  data() {
    return {
      inputValue: ''
    }
  },
  methods: {
    setSelectionColor(color) {
      const style = document.createElement('style')
      style.id = 'dynamic-selection-style'
      style.textContent = `
        .el-input__inner::selection {
          background-color: ${color};
        }
      `

      // 移除旧样式(如果存在)
      const oldStyle = document.getElementById('dynamic-selection-style')
      if (oldStyle) {
        document.head.removeChild(oldStyle)
      }

      document.head.appendChild(style)
    }
  }
}
</script>

注意事项

  1. ::selection伪元素只能修改colorbackground-colortext-shadow等有限属性
  2. 某些浏览器可能需要添加-moz--webkit-前缀
  3. 如果需要兼容IE浏览器,可能需要使用其他方法,因为IE不支持::selection伪元素

高级用法:根据主题动态切换

如果你使用Element-UI的主题切换功能,可以结合CSS变量实现动态切换:

:root {
  --selection-bg-color: #409EFF;
}

.el-input__inner::selection {
  background-color: var(--selection-bg-color);
}

然后在JavaScript中动态修改:root变量:

document.documentElement.style.setProperty('--selection-bg-color', '#ff0000')

这样所有使用该变量的输入框选中颜色都会改变。