// 键盘顶出的高度
var getScrollTop = function getScrollTop() {
  return window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0;
};

var onFocusin = function onFocusin(el) {
  // 等待键盘弹起延迟200毫秒
  setTimeout(function () {
    var scrollTop = getScrollTop();

    if (scrollTop) {
      if (el) {
        el.style.transform = "translateY(" + scrollTop + "px)";
      }
    } else {
      // 滚动高度0，重试一次
      setTimeout(function () {
        if (el) {
          el.style.transform = "translateY(" + getScrollTop() + "px)";
        }
      }, 100);
    }
  }, 200);
};

var onFocusout = function onFocusout(el) {
  if (el) {
    el.style.transform = 'translateY(0)';
  }
};

var timer;

var onScroll = function onScroll(el) {
  el.style.opacity = 0;
  clearTimeout(timer);
  timer = setTimeout(function () {
    el.style.transform = "translateY(" + getScrollTop() + "px)";
    el.style.opacity = 1;
  }, 100);
};

export var sticky = {
  bind: function bind(el) {
    if (navigator.userAgent.includes('iPhone')) {
      document.body.addEventListener('focusin', onFocusin.bind(this, el));
      document.body.addEventListener('focusout', onFocusout.bind(this, el));
      window.addEventListener('scroll', onScroll.bind(this, el));
    }
  },
  unbind: function unbind() {
    document.body.removeEventListener('focusin', onFocusin);
    document.body.removeEventListener('focusout', onFocusout);
    window.removeEventListener('scroll', onScroll);
  }
};