vue指令之解决input失焦页面不回弹的问题

745 阅读1分钟

代码主要考虑了如下2种情况

  • 输入框切换时不做处理
  • 使用keep-alive时需要移除绑定的事件
/*
* 修复ios页面不回弹问题
*/

let scrollY = window.scrollY
let timer = null
const isIos = /iPhone|iPad|iPod/.test(navigator.userAgent)

function checkInput (dom) {
  return dom.tagName.toLowerCase() === 'input' && (dom.type === 'text' || dom.type === 'textarea' || dom.type === 'password')
}

function focusIn (e) {
  if (checkInput(e.target)) {
    scrollY = window.scrollY
    if (timer) clearTimeout(timer)
  }
}

function focusOut (e) {
  if (checkInput(e.target)) {
    // 避免切换输入框的时候页面滚动
    timer = setTimeout(function() {
      window.scrollTo(0, scrollY) 
    })
  }
}

function bind (el, binding) {
  if (!isIos) return
  window.addEventListener('focusin', focusIn)
  window.addEventListener('focusout', focusOut)
}

function unbind (el, binding) {
  if (!isIos) return
  window.removeEventListener('focusin', focusIn)
  window.removeEventListener('focusout', focusOut)
}

export default {
  bind: bind,
  unbind: unbind,
  // 用于手动绑定或解除事件(使用keep-alive的时候可能用的着)
  update: function(el, binding) {
    if (binding.value === undefined) return
    if (binding.value) {
      bind(el, binding)
    } else {
      unbind(el, binding)
    }
  }
}

有什么问题欢迎各位大佬留言