如何检测iOS7 Safari滚动时的高度变化- JavaScript



在iPhone iOS7的Safari中,向下滚动将显示顶部和底部的菜单,向上滚动将隐藏它们-有效地改变屏幕的高度。

我该如何聆听这种轻微的高度变化?

我有一个元素可以根据屏幕的高度改变高度,但在iOS7中它的表现不是很好

要监听窗口大小调整事件,我们可以使用window.addEventListener("resize", myFunction);或使用jQuery $(window).resize(myFunction());

我有一个相关的问题,但相反——在iOS设备上滚动时发生的小窗口大小调整不必要地触发了我的on-resize逻辑。

一个解决方法是忽略一个小的垂直调整(大约40px应该可以)

一个示例解决方案(使用jQuery)

  const ignoreVerticalResizeTreshold= 40;
  let vpHeight= 0;
  let vpWidth= 0;
  
  $(window).resize(function() {

      // Do stuff (on any window resize event)

      // return if no horizontal resize happened and vertical resize is below the set treshold
      if ($(window).innerWidth() === vpWidth && (($(window).innerHeight() >= (vpHeight - ignoreVerticalResizeTreshold / 2)) || ($(window).innerHeight() <= (vpHeight + ignoreVerticalResizeTreshold / 2)))) {
        return;
      }
  
  
      // Do more stuff
  
  
      vpHeight = $(window).innerHeight();
      vpWidth = $(window).innerWidth();
  });

在最近的React项目中,我设置了一个CSS变量为window.innerHeight

const setAppHeight = (): void => {
  const doc = document.documentElement;
  doc.style.setProperty('--app-height', `${window.innerHeight}px`);
};
const debouncedEventHandler = useMemo(
  () => debounce(setAppHeight, 300),
  [],
);
useEffect(() => {
  window.addEventListener('resize', debouncedEventHandler);
  setAppHeight();
  return () => {
    debouncedEventHandler.cancel();
  };
}, []);

这个变量通常是在CSS中设置的,在需要的时候使用

:root {
  --app-height: 100%;
}
.whatever {
  height: var(--app-height);
}

最新更新