Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
296 views
in Technique[技术] by (71.8m points)

javascript - iphone/ipad triggering unexpected resize events

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.

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.

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>

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

    });

});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...