业务场景:

  小程序中有地方用到需要自定义输入验证码或者密码的地方,例如:

 

或者

 

 

这类场景。

需求:n个方框为输入框,框中有光标,且光标随着输入字符移动,输入完成后隐藏输入框/自动校验等

实现:方框用div模拟输入框,然后一个输入框覆盖在方框div上,光标用动画实现

伪代码:

wxml文件:

  1. <view class="input">
  2. <view class="input-item" wx:for="{{4}}" wx:key="index" data-index="{{index}}">
  3. <view class="input-value">{{password[index]}}</view>
  4. <view class="focus {{index === focusIndex ? \'show\': \'hide\'}}"></view>
  5. </view>
  6. <input class="input-password" maxlength="4" bindinput="setValue" bindblur="inputBlur" type="number" focus="{{focus}}"></input>
    </view>

js文件:

  1. Component({
  2. /**
  3. * 组件的初始数据
  4. */
  5. data: {
  6. focusIndex: 0, // 光标所在位置
  7. value: \'\', // 实际输入的值
  8. focus: true, // 是否获得焦点
  9. password: \'\', //替换显示的值*
  10. },
  11. /**
  12. * 组件的方法列表
  13. */
  14. methods: {
  15. setValue (e) {
  16. // 设置光标
  17. var value = e.detail.value
  18. this.setData({
  19. value: value,
  20. focusIndex: value.length,
  21. focus: value.length < 4,
  22. password: \'*\'.repeat(value.length)
  23. })
  24. },
  25. inputBlur (e) {
  26. if (e.detail.value.length === 4) {
  27. this.triggerEvent(\'complated\', {
  28. value: e.detail.value
  29. })
  30. }
  31. }
  32. }
  33. })

wxss文件:

  1. .input {
  2. margin-top: 70rpx;
  3. padding: 0 60rpx;
  4. position: relative;
  5. }
  6. .input-item {
  7. position: relative;
  8. display: inline-block;
  9. width: 90rpx;
  10. height: 90rpx;
  11. border-bottom: 2rpx solid #333;
  12. }
  13. .input-item:not(:first-child) {
  14. margin-left: 26.67rpx;
  15. }
  16. .input-value {
  17. display: inline-block;
  18. position: absolute;
  19. left: 50%;
  20. top: 50%;
  21. transform: translate(-50%, -50%);
  22. font-size: 28rpx;
  23. }
  24. .input-password {
  25. position: absolute;
  26. left: -360rpx;
  27. top: 0;
  28. height: 90rpx;
  29. width: 880rpx;
  30. opacity: 0;
  31. }
  32. .focus {
  33. width: 2rpx;
  34. height: 50rpx;
  35. background-color: #333;
  36. position: absolute;
  37. left: 50%;
  38. top: 50%;
  39. transform: translate(-50%, -50%);
  40. }
  41. .show {
  42. display: block;
  43. animation: blink 1s linear infinite;
  44. }
  45. .hide {
  46. display: none;
  47. }
  48. @keyframes blink {
  49. 0%, 50% {
  50. opacity: 1;
  51. }
  52. 50.01%, to {
  53. opacity: 0;
  54. }
  55. }

大致这样,password可以做明文替换为*

 骚操作就是将input定位在自定义div上面,并且将input的宽度拉大,然后向左移动整个模拟div的宽度,隐藏掉它。

版权声明:本文为xuejiangjun原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/xuejiangjun/p/12704059.html