[英]How to detect iOS7 Safari height change on scrolling - JavaScript
在 iPhone iOS7 上的 Safari 中,向下滚动将在顶部和底部显示菜单,向上滚动将隐藏它们 - 有效地改变了屏幕的高度。
我如何聆听这种轻微的身高变化?
我有一个根据屏幕高度改变高度的元素,但在 iOS7 中它的表现并不好。
要监听窗口调整大小事件,我们可以使用window.addEventListener("resize", myFunction);
或使用 jQuery $(window).resize(myFunction());
我遇到了一个相关的问题,但反过来了——在 iOS 设备上滚动发生的一个小窗口调整大小不必要地触发了我的调整大小逻辑。
一种解决方法可以只是忽略小的垂直调整大小(大约 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 var 设置为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();
};
}, []);
该 var 在 CSS 中正常设置,并在需要时使用
:root {
--app-height: 100%;
}
.whatever {
height: var(--app-height);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.