Skip to content

Instantly share code, notes, and snippets.

@tell-k
Created February 14, 2013 05:30
Show Gist options
  • Save tell-k/4950795 to your computer and use it in GitHub Desktop.
Save tell-k/4950795 to your computer and use it in GitHub Desktop.
mediaクエリーで、アドレスバーを消す前と、消した後で要素の位置(高さ)を固定にしたい時のサンプル
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<style>
/*
初期表示が height: 546px
アドレスバーを消すと height: 615px になる場合
*/
div#hoge {
position: absolute;
top: 50px;
border-bottom:1px solid #f00;
}
@media (min-height: 547px) {
div#hoge {
top: 119px;
border-bottom:1px solid #0f0;
}
}
</style>
</head>
<body>
<div id="hoge">
device height: <span id="height"></span> px &nbsp; <a id="remove-addressbar" href="">バー消す</a>
</div>
<div style="height:1000px;">&nbsp;</div>
</body>
<script type="text/javascript">
//アドレスバーを消す
// http://blog.bluearrowslab.com/smartphone/topicks/492/
var removeAddressBar = function() {
// 端末の向きを算出
var isPortrait = window.innerHeight > window.innerWidth;
// UserAgent から端末の種類を判別
var ua = navigator.userAgent;
var device;
if (ua.search(/iPhone/) != -1 || ua.search(/iPod/) != -1) {
device = "iPhone";
} else if (ua.search(/Android/) != -1) {
device = "Android";
}
// 端末の種類からページの高さを算出
if (device == "Android") {
h = Math.round(window.outerHeight / window.devicePixelRatio);
} else if (device == "iPhone") {
bar = (isPortrait ? 480 : screen.width) - window.innerHeight - (20 + (isPortrait ? 44 : 32));
h = window.innerHeight + bar;
} else {
h = window.innerHeight;
}
// ページの高さをセット
var body = $("body");
if (body.height() < h) {
body.height(h);
}
// ページをスクロール
setTimeout(function() { scrollTo(0, 1); }, 100);
};
$("#remove-addressbar").click(function(e){
e.preventDefault();
removeAddressBar();
});
setInterval(function() {
$("#height").html($(window).height());
}, 1000);
</script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment