项目地址 点击查看
项目演示 点击查看
  1. 首先监听所有的input,有input聚焦时调起数字键盘,通过getBoundingClientRect判断input位置让数字键盘在input附近,失去焦点后则隐藏数字键盘

    let inputElement = document.getElementsByTagName("input");
        [...inputElement].forEach(ipele => {
          ipele.addEventListener("focus", function(e) {
            $this.inputTarget = e.target;
            let scrollTop =
              window.pageYOffset ||
              document.documentElement.scrollTop ||
              document.body.scrollTop;
            let scrollLeft =
              window.pageXOffset ||
              document.documentElement.scrollLeft ||
              document.body.scrollLeft;
            $this.NumberkeyBoardStyle =
              "top:" +
              (e.target.getBoundingClientRect().top +
                scrollTop +
                e.target.offsetHeight) +
              "px;left:" +
              (e.target.getBoundingClientRect().left +
                scrollLeft +
                e.target.offsetWidth) +
              "px";
          });
          ipele.addEventListener("blur", function(e) {
            $this.inputTarget = null;
            $this.NumberkeyBoardStyle = "display:none";
          });
        });
  2. 点击小键盘时阻止默认事件,阻止input失去焦点。

    BoardNumberKeyDown(e) {
          if (e && e.preventDefault) {
            e.preventDefault();
          } else {
            window.event.returnValue = false;
            return false;
          }
        },
  3. 点击小键盘时,根据事件委托,得出点击的数字,然后根据selectionStartselectionEnd获取input中的焦点,将小键盘中的数字插入焦点处,最后焦点右移一位。

    let inputTarget = this.inputTarget;
    let Pointstart = inputTarget.selectionStart;
    let PointEnd = inputTarget.selectionEnd;
    let wordLength = inputTarget.value.length;
    if (e.target.className == "numberTD" && e.target.innerText != "←") {
    inputTarget.value =
      inputTarget.value.slice(0, Pointstart) +
      e.target.innerText +
      inputTarget.value.slice(PointEnd, wordLength);
    //一个小数点和开头不能有小数点
    inputTarget.value = inputTarget.value.replace(/^\./g, "");
    inputTarget.value = inputTarget.value
      .replace(".", "$#$")
      .replace(/\./g, "")
      .replace("$#$", ".");
    inputTarget.selectionStart = Pointstart + 1;
    inputTarget.selectionEnd = Pointstart + 1;
    //让光标显示在input可视区域
    inputTarget.blur();
    inputTarget.focus();
  4. 点击删除键时,删除光标处数字,最后光标右移。

    if (e.target.className == "numberTD" &&
        e.target.innerText == "←" &&
        //PointEnd==0时会复制整个input的value
        PointEnd != 0
        ) {
            inputTarget.value =
              inputTarget.value.slice(0, Pointstart - 1) +
              inputTarget.value.slice(PointEnd, wordLength);
            inputTarget.selectionStart = Pointstart - 1;
            inputTarget.selectionEnd = Pointstart - 1;
            //让光标显示在input可视区域
            inputTarget.blur();
            inputTarget.focus();
          }
  5. 在删除数字和添加数字后要让input失去焦点在获取焦点,不然光标会在最后而不是在input的可视区域,这样子会看不到输入的值,具体可以查看项目

移动的彩虹
334 声望2 粉丝

为无聊而写...