visualViewport Reports Keyboard Insets

visualViewport tracks the visually visible region, so a fixed banner can approximate keyboard height from innerHeight minus the viewport height.

JavascriptData Fetching

Code

javascriptsnippet
18 lines
// visualViewport 报告"真正可见"的视口:软键盘弹出时 height 收缩
const viewport = window.visualViewport;
const banner = document.createElement('output');
banner.style.cssText = 'position:fixed;inset-inline:0;top:0;';
document.body.append(banner);

function syncBanner() {
  // innerHeight 与可视视口高度之差近似软键盘高度
  const keyboardPx = Math.max(0, window.innerHeight - viewport.height);
  banner.textContent = keyboardPx > 150
    ? `keyboard ~= ${Math.round(keyboardPx)}px - keep the focused field above it`
    : 'no keyboard detected';
}

// 键盘弹出/收起与捏合缩放触发 resize;页面被顶起触发 scroll
viewport.addEventListener('resize', syncBanner);
viewport.addEventListener('scroll', syncBanner);
syncBanner();

visualViewport Reports Keyboard Insets: what runs and why

visualViewport Reports Keyboard Insets is built around the function syncBanner.

Points of care

  • The package manager never enters the picture for this snippet.
  • This is browser-side code — document, window will not resolve in Node.

Putting it to use

Signature: function syncBanner()

Core lines

viewport.addEventListener('resize', syncBanner);
viewport.addEventListener('scroll', syncBanner);

Interactive Tools for This Topic

FAQ

Does visualViewport Reports Keyboard Insets run in plain Node.js?
No — it touches `document` and `window`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.