媒体查询和设备方向更改

3
我有以下代码。我想实现的是在移动设备从竖屏模式切换到横屏模式时(像 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像素,因此应该使用第二个规则。我该怎么做呢?
1个回答

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));

1
这不仅发生在iPhone上,也发生在Galaxy S(第一代)上。 - Illes Peter

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接