在Vue项目中动态修改Element-UI的el-input输入框选中状态(selection)的背景色,可以通过以下几种方式实现:
/* 全局样式 */
.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>
<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>
<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>
::selection
伪元素只能修改color
、background-color
、text-shadow
等有限属性-moz-
或-webkit-
前缀::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')
这样所有使用该变量的输入框选中颜色都会改变。