Reset scale/width/zoom of Safari on iPhone using JavaScript/onorientationchange

前端 未结 7 1122
臣服心动
臣服心动 2021-02-02 00:24

I am displaying different content depending on how the user is holding his/her phone using the onorientationchange call in the body tag. This works great - I hide one div while

7条回答
  •  清歌不尽
    2021-02-02 01:07

    Using meta tags for this does not work. I've tried every combination of meta tags and orientationchange and gesturechange events possible, I tried timeouts and all kinds of fancy javascript, then I found this: https://github.com/scottjehl/iOS-Orientationchange-Fix

    via this related question: How do I reset the scale/zoom of a web app on an orientation change on the iPhone?

    On that post, Andrew Ashbacher posted a link to the code written by Scott Jehl:

    /*! A fix for the iOS orientationchange zoom bug. Script by @scottjehl, rebound by @wilto.MIT License.*/(function(m){if(!(/iPhone|iPad|iPod/.test(navigator.platform)&&navigator.userAgent.indexOf("AppleWebKit")>-1)){return}var l=m.document;if(!l.querySelector){return}var n=l.querySelector("meta[name=viewport]"),a=n&&n.getAttribute("content"),k=a+",maximum-scale=1",d=a+",maximum-scale=10",g=true,j,i,h,c;if(!n){return}function f(){n.setAttribute("content",d);g=true}function b(){n.setAttribute("content",k);g=false}function e(o){c=o.accelerationIncludingGravity;j=Math.abs(c.x);i=Math.abs(c.y);h=Math.abs(c.z);if(!m.orientation&&(j>7||((h>6&&i<8||h<8&&i>6)&&j>5))){if(g){b()}}else{if(!g){f()}}}m.addEventListener("orientationchange",f,false);m.addEventListener("devicemotion",e,false)})(this);
    

    That is a solution wrapped nicely in an IIFE so you don't have to worry about name-space issues.

    Just drop it in to your script (not into document.ready() if you're using jQuery) and viola!

    All it does is disable zoom on devicemotion events that indicate that orientationchange is imminent. It's the best solution I've seen because it actually works and doesn't disable zoom.

    EDIT: this approach is not always reliable, especially when you are holding the ipad at an angle. also, i don't think this event is available to gen 1 ipads

提交回复
热议问题