uni-app switch组件设置大小失败

发布于 1周前 作者 ionicwang 来自 Uni-App

uni-app switch组件设置大小失败

3 回复

使用css3 的transform 缩小switch


如需调节switch大小,可通过css的scale方法调节,如缩小到70%style=“transform:scale(0.7)”

uni-app 中,switch 组件默认的大小是由框架控制的,通常直接通过样式设置大小可能不会生效,因为 switch 组件是一个原生控件,其样式受限于平台原生渲染机制。不过,你可以通过一些技巧来间接实现调整 switch 组件大小的需求。

方法一:使用缩放变换(Transform)

虽然直接设置宽度和高度无效,但你可以通过 CSS 的 transform: scale() 属性对 switch 组件进行缩放。这不会影响 switch 的交互区域,只是视觉上进行了缩放。

<template>
  <view class="container">
    <switch class="custom-switch" :checked="isChecked"></switch>
  </view>
</template>

<script>
export default {
  data() {
    return {
      isChecked: false
    };
  }
};
</script>

<style scoped>
.container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}

.custom-switch {
  transform: scale(0.5); /* 缩小到原来的50% */
  transform-origin: center center; /* 确保缩放中心为组件中心 */
}
</style>

方法二:自定义开关组件

如果缩放变换不能满足需求,或者你需要更精细的控制,可以考虑自定义一个开关组件,使用 viewimage 等元素模拟开关的外观和行为。

<template>
  <view class="custom-switch" :class="{active: isChecked}" @tap="toggleSwitch">
    <view class="knob"></view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      isChecked: false
    };
  },
  methods: {
    toggleSwitch() {
      this.isChecked = !this.isChecked;
    }
  }
};
</script>

<style scoped>
.custom-switch {
  width: 50px;
  height: 25px;
  background-color: gray;
  border-radius: 12.5px;
  position: relative;
  cursor: pointer;
}

.custom-switch.active {
  background-color: green;
}

.knob {
  width: 23px;
  height: 23px;
  background-color: white;
  border-radius: 50%;
  position: absolute;
  top: 1px;
  left: 1px;
  transition: transform 0.3s;
}

.custom-switch.active .knob {
  transform: translateX(25px);
}
</style>

在这个例子中,我们创建了一个自定义的开关组件,通过改变 .knob 的位置来模拟开关的打开和关闭状态。这种方法提供了更大的灵活性,允许你完全控制开关的外观和行为。

回到顶部