uniapp密码框如何添加小眼睛功能

在uniapp中,如何给密码输入框添加小眼睛功能,实现密码的显示与隐藏切换?求具体实现方法和代码示例。

2 回复

在uniapp中,可以通过动态绑定input的type属性实现小眼睛功能。使用type="password"type="text"切换,配合图标点击事件即可。

示例代码:

<template>
  <view>
    <input :type="showPassword ? 'text' : 'password'" />
    <text @click="showPassword = !showPassword">👁️</text>
  </view>
</template>

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

在 UniApp 中,为密码框添加“小眼睛”功能(切换密码可见性),可以通过结合 input 组件的 password 属性和图标点击事件来实现。以下是详细步骤和代码示例:

实现思路

  1. 使用 input 组件,设置 password 属性绑定一个变量(如 isPassword),控制是否以密文显示。
  2. 在输入框右侧添加一个图标(如眼睛图标),通过点击事件切换 isPassword 变量的值。
  3. 使用 Flex 布局或绝对定位将图标对齐到输入框右侧。

代码示例

<template>
  <view class="input-container">
    <input 
      :password="isPassword" 
      placeholder="请输入密码" 
      class="password-input"
    />
    <view class="eye-icon" @click="togglePasswordVisibility">
      <image 
        :src="isPassword ? '/static/eye-close.png' : '/static/eye-open.png'" 
        class="icon"
      />
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      isPassword: true // 初始状态为密码不可见
    };
  },
  methods: {
    togglePasswordVisibility() {
      this.isPassword = !this.isPassword; // 切换状态
    }
  }
};
</script>

<style scoped>
.input-container {
  position: relative;
  display: flex;
  align-items: center;
}
.password-input {
  flex: 1;
  padding-right: 80rpx; /* 为图标留出空间 */
}
.eye-icon {
  position: absolute;
  right: 20rpx;
  padding: 10rpx;
}
.icon {
  width: 40rpx;
  height: 40rpx;
}
</style>

关键点说明

  • 图标资源:准备两张图片(睁眼和闭眼),放在 static 目录下,例如 eye-open.pngeye-close.png
  • 布局:使用 position: absolute 将图标定位到输入框右侧,并通过 padding-right 避免文字与图标重叠。
  • 状态切换:点击图标时,通过 togglePasswordVisibility 方法切换 isPassword 的值,从而改变输入框的显示类型。

注意事项

  • 如果使用图标字体(如 UniApp 内置图标),可替换 image 组件为 text 组件,并调整样式。
  • 测试时确保图标路径正确,在不同平台(如 H5、小程序)上显示正常。

以上代码简洁高效,实现了密码框的可见性切换功能。

回到顶部