【问题标题】:Media queries and device orientation change媒体查询和设备方向变化
【发布时间】:2012-01-28 14:52:47
【问题描述】:

我有下面的代码。我想要实现的是在移动设备的样式之间切换,将方向从纵向更改为横向(具有大分辨率的设备,如 iPhone 4 或 Galaxy S)

<!doctype html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0" />

    <title>KUBIK</title>
    <style>
        #mobile,
        #tablet { display: none; }

        @media screen and (max-width: 767px) {
            body { background-color: #FF0000; }
            #mobile { display: block; }
        }
        @media screen and (min-width: 768px) and (max-width: 1024px) {
            body { background-color: #00FFFF; }
            #tablet { display: block; }
        }       
    </style>

</head>
<body>
    <div id="mobile">MOBILE</div>
    <div id="tablet">TABLET</div>
</body>
</html>

在横向 iPhone 4 的宽度为 960 像素,所以第二条规则应该出现。我该如何实现呢?

【问题讨论】:

    标签: css media-queries device-orientation


    【解决方案1】:

    iPhone 在方向切换时出现错误。请参阅 this gist 以获取 javascript 修复

    // Rewritten version
    // By @mathias, @cheeaun and @jdalton
    
    (function(doc) {
    
        var addEvent = 'addEventListener',
            type = 'gesturestart',
            qsa = 'querySelectorAll',
            scales = [1, 1],
            meta = qsa in doc ? doc[qsa]('meta[name=viewport]') : [];
    
        function fix() {
            meta.content = 'width=device-width,minimum-scale=' + scales[0] + ',maximum-scale=' + scales[1];
            doc.removeEventListener(type, fix, true);
        }
    
        if ((meta = meta[meta.length - 1]) && addEvent in doc) {
            fix();
            scales = [.25, 1.6];
            doc[addEvent](type, fix, true);
        }
    
    }(document));
    

    【讨论】:

    • 这不仅发生在 iPhone 上,也发生在 Galaxy S(第一代)
    猜你喜欢
    • 1970-01-01
    • 2015-11-20
    • 2019-09-22
    • 2013-04-09
    • 2014-02-25
    • 2017-05-14
    • 2012-05-18
    • 2021-03-10
    • 2011-08-09
    相关资源
    最近更新 更多