gpt4 book ai didi

javascript - 在页面加载时获取 safe-area-inset-bottom

转载 作者:行者123 更新时间:2023-12-05 06:57:26 26 4
gpt4 key购买 nike

我正在使用下面的代码获取 iPhone 底部的安全区域。

如果我调用 getSafeArea()deviceready 之后立即,它有时会返回 0 而不是所需的值。我需要使用另一个事件监听器来代替 deviceready 吗? ?

document.addEventListener('deviceready', () => {
console.log('safeArea1', getSafeArea()); // Sometimes returns 34 and sometimes 0 -> bad
setTimeout(() => console.log('safeArea2', getSafeArea()), 1000); // Always returns 34 -> good
});

function getSafeArea() {
return +getComputedStyle(document.documentElement).getPropertyValue('--safe-area-bottom').slice(0, -2);
}

我的 <head> 中也有以下内容用于创建 CSS 变量的标签 --safe-area-bottomgetSafeArea()阅读:

<style>
:root {
--safe-area-bottom: env(safe-area-inset-bottom);
}
</style>

(一般做法来自:https://benfrain.com/how-to-get-the-value-of-phone-notches-environment-variables-env-in-javascript-from-css/)

最佳答案

我也想不出比 setTimeout 更好的解决方案。一个 on 'load' 监听器只在部分时间工作,但如果不起作用,我决定在 2^n 时间内多次重新计算该值。通过这种方式,我们可以确保几乎在值可用时立即获得值,但我们只需这样做 13 次即可完成 8 秒的等待。

window.addEventListener('load', () => {
computeValue()
})

// Sometimes that doesn't work. So for the next 8 seconds we will recompute the value
for (let i = 0; i < 13; i++) {
setTimeout(() => {
computeValue()
}, 2 ** i)
}

这对我来说效果很好,是在某种事件监听器中获取值的下一个最佳解决方案。

关于javascript - 在页面加载时获取 safe-area-inset-bottom,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64891541/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com