iPhone用サイトで、画像を縦横ともに画面幅いっぱいにリサイズさせる //iPhone

iPhone用サイトを作る場合は、画面サイズが縦横で異なります。
画面解像度は320×480なので、コンテンツの幅が320と480の両方に対応して作ります。

表示の際の幅はmeta内のviewportで設定しますが、画面閲覧中に縦横を切り替えた場合の画像サイズの切替を行いたくていろいろ調べました。
下のサンプルでは、SitePoint内の記事を参考に、div#mainimage内のimg1.jpgの幅を、縦の場合は320×160、横の場合、480×240で表示します。
その他レイアウト等もCSS内に同様に記述することで、縦横で分岐することが出来ます。
今回のキーポイントは、iPhoneの表示角度を利用するときに使う、window.orientationです。window.orientationchangeで、縦横切替の際のトリガーになります。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:spry="http://ns.adobe.com/spry">
<head>

<meta name="viewport" content="initial-scale=1.0; maximum-scale=1.0; user-scalable=0;" />
<script type="text/javascript">
window.addEventListener('load', setOrientation, false); 
window.addEventListener('orientationchange', setOrientation, false);

function setOrientation() { 
     var orient = Math.abs(window.orientation) === 90 ? 'landscape' : 'portrait'; 
     var cl = document.body.className; 
     cl = cl.replace(/portrait|landscape/, orient); 
     document.body.className = cl; 
}
</script>   

<style>
body.portrait #main_image img{
    width:320px;
    height:160px;
}
body.landscape #main_image img{
    width:480px;
    height:240px;
}
</style>
</head>

<body class="portrait">
<div id="main_image">
  <img src="img1.jpg" width="320" height="160" />
  </div>
</body>


参考記事
Sitepoint : New Articles, Fresh Thinking for Web Developers and Designers
http://articles.sitepoint.com/print/iphone-development-12-tips


Bookmark and Share


ブックマークに追加