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 属性和图标点击事件来实现。以下是详细步骤和代码示例:
实现思路
- 使用 input组件,设置password属性绑定一个变量(如isPassword),控制是否以密文显示。
- 在输入框右侧添加一个图标(如眼睛图标),通过点击事件切换 isPassword变量的值。
- 使用 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.png和eye-close.png。
- 布局:使用 position: absolute将图标定位到输入框右侧,并通过padding-right避免文字与图标重叠。
- 状态切换:点击图标时,通过 togglePasswordVisibility方法切换isPassword的值,从而改变输入框的显示类型。
注意事项
- 如果使用图标字体(如 UniApp 内置图标),可替换 image组件为text组件,并调整样式。
- 测试时确保图标路径正确,在不同平台(如 H5、小程序)上显示正常。
以上代码简洁高效,实现了密码框的可见性切换功能。
 
        
       
                     
                   
                    

