Dynamically modify the el-input style; dynamically modify the elmentUI element style; css variables

insert image description here

Scenario: Normally, we dynamically modify the style of the div element, using :style and :class; but when we want to dynamically modify the component style of the element, such as the font color of el-input, because the style of el-input is deeply nested, What we need to modify is actually the color of the .el-input__inner style, but we can't get this class name in html.

解决办法:使用css变量修改


1. What are CSS variables?

1. css variables

For css variables, please refer to this article

Note: 1. When declaring a variable, two hyphens should be added in front of the variable name –
2. The variable is wrapped with the var() function, and the second parameter can also be used to indicate the default value of the variable. If the variable does not exist, this default value will be used

In the following code, two variables are declared:--shadow、--size

div {
    
    
    font-size: var(--size, 18px);
    box-shadow: var(--shadow);
}

2. Modify the font color of el-input

1. Originally modify the font color normally

/deep/ .el-input__inner {
    
    
  color: red
}

2. Dynamically modify the font color of el-input

Ideas:
1. Introduce a variable to css--inputColor

        /deep/ .el-input__inner {
    
    
          color: var(--inputColor); //使用css变量 注意变量前需要加 --
        }

2. Vue declares a variable color colorValsuch as #606266

data (){
    
    
	return {
    
    
		colorVal: '#606266',
	}
}

3. Where you need to modify, --inputColorassign a value to the variable

<el-input v-model="valueStr" :style="{ '--inputColor': colorVal}"></el-input>

4. Dynamic js colorValcan be modified

this.colorVal = 'red'

Need to pay attention: --inputColorit is the css variable, which helps to guide, colorValis the set style value

3、以下代码可直接复制

<template>
  <div>
    <el-input v-model="valueStr" :style="{ '--inputColor': colorVal}" @input="change1"></el-input>
  </div>
</template>

<script>
export default {
    
    
  data () {
    
    
    return {
    
    
      valueStr: '',
      colorVal: '#606266',
    }
  },
  created () {
    
    
  
  },
  methods: {
    
    
    change1 () {
    
    
      var r = Math.floor(Math.random() * 256)
      var g = Math.floor(Math.random() * 256)
      var b = Math.floor(Math.random() * 256)
      // 设置随机色
      var color = '#' + r.toString(16) + g.toString(16) + b.toString(16)
      this.colorVal = color
    },
  },
}
</script>

<style lang="less" scoped>
/deep/ .el-input__inner {
    
    
  color: var(--inputColor); //使用css变量 注意变量前需要加 --
}
</style>

Summarize

其他的组件或者组件库,动态修改样式,同样道理

Guess you like

Origin blog.csdn.net/i_am_a_div/article/details/127861858