iPad 方向更改事件处理程序中的 Javascript 变量已损坏

发布于 2024-12-12 04:19:30 字数 443 浏览 0 评论 0原文

我正在为 iPad 开发一个 Html 和 Javascript 目录页面滑块,它以纵向方式显示一页,以横向方式显示两页。

用于维护目录状态的两个变量在事件处理程序中的每次方向变化时进行操作。

当我快速翻动 iPad 时,变量就被破坏了。当我像平常一样操作时(也就是说,相当慢),它们就很好。

我尝试使用 locked 变量来防止处理程序在尚未完成的情况下运行,即移动 Safari 在方向更改时中断 Javascript 执行:

function updateOrientation() {
    if (locked) return;
    locked = true;
    ...

但是,情况似乎从未如此;处理程序总是在再次调用之前完成。

那么,变量是如何被破坏的呢?

有什么想法吗?

I am developing an Html and Javascript catalogue pageslider for iPad which shows one page in portrait and two pages in landscape.

Two variables for maintaining the state of the catalogue are manipulated on each orientation change in an event handler.

The variables are corrupted when I toss and turn the iPad quickly. They are fine when I operate it as one would normally do (rather slowly, that is).

I've tried using a locked variable to prevent the handler from being run if it has not completed yet, i.e. in case mobile Safari breaks Javascript execution on orientation change:

function updateOrientation() {
    if (locked) return;
    locked = true;
    ...

However, this never seems to be the case; the handler always finishes before it is called again.

Hence, how do the variables get corrupted?

Any ideas?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

一枫情书 2024-12-19 04:19:30

我已经找到答案了。

通常,我希望方向更改事件意味着方向的更改,即 window.orientation 应该更改值(纵向 -> 横向或横向 -> 纵向)。

然而,快速的翻来覆去会导致事件处理程序被连续调用两次,并从 window.orientation 读取相同的值。这是意想不到的并且会破坏状态变量。

我通过保持最后一个已知的方向解决了这个问题,如果该值自上次以来没有改变,则立即返回。

function updateOrientation() {
if (lastOrientation == isPortrait()) return; // prevent erroneous orientation changes
lastOrientation = isPortrait();

I've found the answer.

Normally, I would expect the orientation change event to imply a change in orientation, i.e. window.orientation should change value (portrait -> landscape or landscape -> portrait).

However, quick tosses and turns cause the event handler to be called two consecutive times with the same value being read from window.orientation. This is unexpected and corrupts the state variables.

I solved the problem by keeping the last known orientation and immediately return if the value hasn't changed since last time.

function updateOrientation() {
if (lastOrientation == isPortrait()) return; // prevent erroneous orientation changes
lastOrientation = isPortrait();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文