媒体查询和设备方向更改

时间:2012-01-28 14:52:47

标签: css media-queries device-orientation

我有以下代码。我想要实现的是在移动设备的样式之间切换更改方向从纵向到横向(具有大分辨率的设备,如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的宽度为960px,因此第二条规则应该出现。我将如何实现这一目标?

1 个答案:

答案 0 :(得分:1)

当方向切换时,iPhone有一个错误。有关javascript修复的信息,请参阅this gist

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