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

查看:18
本文介绍了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 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.

这是一个简单的例子:

<!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 函数之前,存储窗口宽度并检查它是否确实发生了变化:

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天全站免登陆