iphone / ipad触发意外调整大小事件 [英] iphone/ipad triggering unexpected resize events

查看:94
本文介绍了iphone / ipad触发意外调整大小事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用我的网站的移动版本。我尽可能地使用媒体查询和CSS,但我也使用一些javascript,例如,将我的导航转换为更小的设备上的折叠/展开列表,以节省空间。

I'm working on a mobile version of my site. I'm using media queries and CSS as much as possible, but I'm also using some javascript to, for example, turn my navigation into a collapse/expand list on smaller devices to save room.

要处理所有这些,我试图使用window.resize事件。这可以让魔法在桌面浏览器上调整大小时发生,但是当我没有期望它们时,我会在iPad / iPhone上调整大小事件。

To handle all of this, I was attempting to use the window.resize event. This allows the magic to happen on desktop browsers while they're resized, but I'm getting resize events on iPad/iPhone when I'm not expecting them.

On桌面浏览器,我只得到一个调整大小事件,如果我实际调整窗口大小。在移动浏览器上,当我改变方向(预期)时,我得到调整大小事件,但是当我切换到展开/折叠时,我也得到它。

On desktop browsers, I only get a resize event if I actually resize the window. On mobile browsers I get the resize event when I change orientation (expected), but I also get it when I toggle to expand/collapse something.

这里有一个简单的例子:

Here's a simple example:

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<title>Resize test</title>
<style>
.box {height: 10000px; background: green; display: none;}
</style>
<script>
$(function(){
    $(".opener").click(function(){
        $(".box").slideToggle();
    });
    $(window).resize(function(){
        alert("resized");
    });
});
</script>
</head>

<body>
<a href="#" class="opener">Open/close me</a>
<div class="box"></div>
</body>
</html>

当您在桌面浏览器上单击链接时,没有警报。点击iPhone / iPad上的链接,您会收到警报。

When you click the link on a desktop browser, no alert. Click the link on iPhone/iPad, you get the alert. What's the deal?

推荐答案

存储窗口宽度并检查它是否实际改变,然后再进行 $(window).resize function:

Store the window width and check that it has actually changed before proceeding with your $(window).resize function:

jQuery(document).ready(function($) {

    // Store the window width
    var windowWidth = $(window).width();

    // Resize Event
    $(window).resize(function(){

        // Check window width has actually changed and it's not just iOS triggering a resize event on scroll
        if ($(window).width() != windowWidth) {

            // Update the window width for next time
            windowWidth = $(window).width();

            // Do stuff here

        }

        // Otherwise do nothing

    });

});

这篇关于iphone / ipad触发意外调整大小事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆