[英]$(window).height() and window.innerHeight don't give the same output
[英]calling window.innerHeight upon window resize event doesn't give correct height
我正在使用window.onresize偵聽視口大小的更改,因此我可以適當地縮放內容(這是游戲界面,因此似乎最容易使用window.onresize + CSS縮放,歡迎其他建議)。
但是,在某些瀏覽器上,在觸發onresize之后立即調用window.innerHeight或window.innerWidth會產生錯誤的結果。
這是一個最小的工作示例:
<html>
<head>
<title>Firefox Resize bug</title>
<link
rel="manifest"
href='data:application/manifest+json,{ "name": "onresize bug", "display":"standalone"}'
/>
</head>
<body>
Height: <span id="heightField"></span>
<br />
Width: <span id="widthField"></span>
<script>
const heightField = document.getElementById("heightField");
const widthField = document.getElementById("widthField");
const updateSize = () => {
heightField.textContent = window.innerHeight;
widthField.textContent = window.innerWidth;
};
window.onresize = updateSize;
updateSize();
</script>
</body>
</html>
當您更改方向,高度和寬度正確更新時,這在iOS 12 Safari中可以正常工作。
但是,它不能在iOS Firefox / Chrome上運行(至少不能可靠地運行),並且如果將此應用程序添加到iPhone的主屏幕上也無法運行(請參見上面示例中的清單)
我一直在通過onresize事件后觸發我的updateSize 500ms來解決這個問題,但是這里到底發生了什么?
初始規模和縮小以適合您的問題。
使用視口元標記控制移動瀏覽器上的布局
將視口元數據添加到您的頭部
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
這是webkit中的錯誤。
https://bugs.webkit.org/show_bug.cgi?id=185886
在iOS中,當設備切換方向時,WKWebView中會觸發
window.onresize
事件。 但是,如果WKWebView放置為具有“自動布局”,則window.innerWidth
和window.innerHeight
將報告window.onresize
事件處理程序中的錯誤值。 但是,如果WKWebView在不使用“自動布局”的情況下手動放置,則window.innerWidth
和window.innerHeight
將在事件處理程序中報告正確的值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.