媒体查询和设备方向更改 [英] Media queries and device orientation change

查看:78
本文介绍了媒体查询和设备方向更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've got the code below. What I would like to achieve is to switch between styles of a mobile device changes orientation from portrait to landscape (devices that have a large resolution like iPhone 4 or 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,因此应该引入第二条规则.我将如何实现?

In landscape the iPhone 4 has a width of 960px, so the second rule should come in. How would I achieve that?

推荐答案

方向切换时,iPhone出现错误.请参见此要点以获取JavaScript修复

The iPhone has a bug when the orientation switches. See this gist for a javascript fix

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

这篇关于媒体查询和设备方向更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆