在Element UI的Vue项目中,要动态改变el-input组件选中时的背景颜色,可以通过以下几种方法实现:
/* 全局样式或在组件样式中 */
.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>
<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>
!important
是为了覆盖Element UI的默认样式::v-deep
或/deep/
(取决于Vue版本).el-input__inner {
transition: background-color 0.3s ease;
}
以上方法可以根据项目需求选择使用,方法一和方法二更为简洁,方法三适用于需要更复杂动态样式控制的场景。