兼容quill手机键盘遮住的问题

176 阅读1分钟

getBounds

返回给定选区相对于编辑器容器的的像素位置和尺寸。用户的当前选区不需要在索引下。用于计算提示框的位置。

方法

getBounds(index: Number, length: Number = 0):
  { left: Number, top: Number, height: Number, width: Number }

selection-change

但用户或API引起选择项改变时触发,返回表示选择项边界的范围数据。空范围(null)表示选择项丢失(通常是因为编辑器失去焦点)。你也可以通过检查触发的范围是否为空(null),来把这个事件当做一个焦点改变事件。

用传入source值"silent"调用引起文本改变的API的情况不能触发 selection-change事件。这对消除 selection-change的副作用是有用的,比如,键入会引起选择项改变,但键入每个字符都触发selection-change事件是很烦人的。

回调签名

handler(range: { index: Number, length: Number },
        oldRange: { index: Number, length: Number },
        source: String)

具体方法

quill.on("selection-change", function (range, oldRange, source) {
      // 计算光标位置和尺寸
      
      const cursorBounds = quill.getBounds(range.index, 0);
      // 计算键盘高度(使用约等于值)
      // const keyboardHeight = window.innerHeight * 0.3;
      // alert(window.innerHeight)
      // 计算光标底部相对于窗口顶部的位置
      const cursorBottom = cursorBounds.top + cursorBounds.height;
      // 计算可见区域的底部相对于窗口顶部的位置
      const h = quill.container.offsetHeight;
      setTimeout(() => {
        const visibleBottom = quill.container.offsetHeight;
        const keyboardHeight = h - quill.container.offsetHeight;
        if (keyboardHeight > 0 && cursorBottom > visibleBottom) {
          // Toast("滚动")
          const scrollTop = quill.scrollingContainer.scrollTop + (cursorBottom - visibleBottom);
          quill.scrollingContainer.scrollTop=scrollTop;
        } else {
          const newBounds = quill.getBounds(range.index, 0);
          if (newBounds.top<0) {
            const scrollTop = quill.scrollingContainer.scrollTop +newBounds.top;
            quill.scrollingContainer.scrollTop=scrollTop;
          }
        }
      }, 180);
    });

后续发现存在兼容问题

有的手机键盘不会顶起内容,卧槽一声~~~~

只能通过底层传过来键盘的高度来判断

    quill.on("selection-change", function (range, oldRange, source) {
      // 计算光标位置和尺寸
      const h = quill.container.offsetHeight;
      setTimeout(() => {
        if (that.keyboardHeight > 0) {
          const cursorBounds = quill.getBounds(range.index, 0);
          const cursorBottom = cursorBounds.top + cursorBounds.height;
          let visibleBottom = h - that.keyboardHeight;
          visibleBottom=visibleBottom>100?visibleBottom:quill.container.offsetHeight;
          if (cursorBottom > visibleBottom) {
            const scrollTop =
              quill.scrollingContainer.scrollTop + (cursorBottom - visibleBottom);
            quill.scrollingContainer.scrollTop = scrollTop;
          } else {
            const newBounds = quill.getBounds(range.index, 0);
            if (newBounds.top < 0) {
              const scrollTop = quill.scrollingContainer.scrollTop + newBounds.top;
              quill.scrollingContainer.scrollTop = scrollTop;
            }
          }
        }
      }, 180);
    });

这里的 that.keyboardHeight是调用uniapp的获取键盘高度获取