问题
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>
In landscape the iPhone 4 has a width of 960px, so the second rule should come in. How would I achieve that?
回答1:
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));
来源:https://stackoverflow.com/questions/9046152/media-queries-and-device-orientation-change