Element之el-switch上显示文字

本文介绍如何在 Element UI 的 Switch 组件上显示开和关的文字,通过自定义样式和属性实现。适用于希望增强 UI 组件交互效果的前端开发者。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

如果我们想要在Element组件库中的switch开关组件上显示文字该怎么做?

1.Html部分

<el-switch 
  class="demo" 
  v-model="value" 
  active-text="是" 
  inactive-text="否" 
/>

 2.css部分

 

.demo >>> .el-switch__label {
   position: absolute;
   display: none;
   color: #fff;
 }
 .demo >>> .el-switch__label--right {
   z-index: 1;
   left: -3px;
 }
 .demo >>> .el-switch__label--left {
   z-index: 1;
   left: 19px;
 }
 .demo >>> .el-switch__label.is-active {
   display: block;
 }
 .demo >>> .el-switch .el-switch__core,
 .el-switch .el-switch__label {
   width: 50px !important;
 }

 3.效果图

 至此我们就完成了

Element Plus 的 `el-switch` 组件是一个用于显示二选一状态的开关按钮,通常用于切换某种配置或选项。如果你想在 `el-switch` 中加入自定义的切换图标,你可以通过覆盖默认样式或者使用自定义组件的方式来实现。 1. **覆盖默认样式**:如果你熟悉 CSS,可以在 `.el-switch__core` 或者 `.el-switch__inner` 这样的选择器上添加样式,替换默认的圆点或线条图标。例如: ```css .el-switch__inner::before { content: url('path-to-your-custom-icon.png'); } ``` 记得替换 `'path-to-your-custom-icon.png'` 为你实际的图标路径。 2. **使用自定义组件**:如果你需要更复杂的交互或者定制,可以创建一个自定义的开关组件,并将其作为 `el-switch` 的替代。这通常涉及拆分原生组件的结构,然后将你的图标包装在其中。这种方法更灵活,但是会增加开发复杂度。 在 Vue 项目中,你会创建一个新的 Vue 组件并覆盖 `el-switch` 的模板结构,比如: ```html <template> <div :class="switchClass" @click="toggle"> <span class="custom-switch__handle" :style="{ left: handleStyle.left }"></span> </div> </template> <script> export default { name: 'CustomSwitch', props: { onText: String, offText: String, iconOn: { type: String, default: 'your-icon-on' }, iconOff: { type: String, default: 'your-icon-off' } }, computed: { switchClass() { return this.isActive ? 'is-active' : ''; }, handleStyle() { return { transform: `translateX(${this.isActive ? 0 : '100%'})`, background: this.isActive ? '#007aff' : '' }; } }, methods: { toggle() { // 控制状态改变 } } }; </script> ``` 别忘了导入并使用这个自定义组件替换原始的 `el-switch`。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值