Search

画像を先読み

unknown

「ロールオーバーボタンなどマウスイベントで画像入替をしている」、「画像を多用したレイアウト」の場合などは、ページを表示する前に使用画像を読み込んでおくことで、画像切替動作や画面表示がスムーズにいきます。

ページを読み込む(onLoad)時に、使用画像をキャッシュとして読み込みます。 以下の例では、body要素のonload属性に画像先読み処理を記述しています。

<!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" xml:lang="ja" lang="ja">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta http-equiv="Content-Language" content="ja" />
    <meta http-equiv="Content-Script-Type" content="text/javascript" />
    <title>画像のプレロード</title>
    <script type="text/javascript">
        /* 先読みする画像の配列 */
        var images_ary=new Array(
        'images/1.gif',
        'images/2.gif',
        'images/3.gif',
        'images/4.gif',
        'images/5.gif'
        );
        /* 画像先読み処理関数 */
        function preLoad(imgAry) {
            var imgMax=imgAry.length;
            var images=new Array(imgMax);
            for (var i=0; i<imgMax; i++) {
                images[i]=new Image();
                images[i].src=imgAry[i];
            }
        }
    </script>
    </head>
    <!-- ページ読込時に画像を先読みさせる -->
    <body onload="preLoad(images_ary)">

    </body>
</html>

JavaScriptでボタンのロールオーバー

unknown

⇒ スタイルシートを使用したボタンのロールオーバーボタンはコチラにあります。

ロールオーバー1

画像をクリックした時(onClickイベント発生時)に、画像のパス(SRC属性)を切り替えてロールオーバーさせる例。

サンプルを見る
<script type='text/javascript'>
    /* JavaScriptでロールオーバー */
    function btnRollOverForJS(obj){
        var img_on="/content/img/btn/btn_on.gif";
        var img_off="/content/img/btn/btn_off.gif";
        obj.src=(obj.src.indexOf("btn_on")!=-1) ? img_off : img_on;
    }
</script>

<form action="#">
    <img src="/content/img/btn/btn_off.gif" 
        width="59" height="18" 
        alt="サンプルボタン" 
        onmouseover="btnRollOverForJS(this)" onmouseout="btnRollOverForJS(this)" />
</form>
サンプルボタン

ロールオーバー2(DOM+イベントハンドラ)

外部JSに、ページロード時に画像のマウスオーバー、マウスアウトイベントを設定し、各イベント発生時に画像のパス(SRC属性)を切り替えてロールオーバーさせる例。

サンプルを見る
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="utf-8">
    <title>ロールオーバーサンプル(DOM+イベントハンドラ)</title>
    <script>
        window.onload=function(){
            document.getElementById("sw").onmouseout=function(){
                document.getElementById("swIMG").src="/content/img/btn/btn_off.gif";
                //this.firstChild.srcでもいい。
                //IMG要素のonmouseoutイベントがうまく取得できないようなので、span要素のイベントを取得。
            }
            document.getElementById("sw").onmouseover=function(){
                document.getElementById("swIMG").src="/content/img/btn/btn_on.gif";
                //this.firstChild.srcでもいい。
            }
        }
    </script>
</head>
<body>
    <p>
        <span id="sw"><img id="swIMG" src="/content/img/btn/btn_off.gif" alt="サンプルボタン" /></span>
    </p>
</body>
</html>

関連コンテンツ

Q. このサイトの情報はお役に立ちましたでしょうか?

投票する 投票結果を見る

管理人に【web拍手】を送るweb拍手(1行メッセージも送れます♪)

pagetop

polarized women