MATz Tech

webの技術的なことを中心にいろいろと

ファイル選択した画像をモーダル表示

前回に引き続き、画像のファイル選択ネタです。

今回は、ファイル選択した画像をモーダルウインドウで表示します。
jQueryプラグインでこれ系のはけっこうあるんですけど、敢えてプラグインに頼らずやってみました!


htmlとcssはこんな感じです。

<div id="modal-content">
    <img src="" id="preview" width="500px" />
    <a id="modal-cancel" class="button-link">cancel</a>
    <a id="modal-ok" class="button-link">OK</a>
</div>
<input type="file" id="imageSelect" onChange="imgSelect();" />
/*モーダルウィンドウ*/
#modal-content{
    width:50%;
    margin:1.5em auto 0;
    padding:10px 20px;
    border-radius: 10px;
    background:#fff;
    z-index:2;
    position:fixed;
    display:none;
}
.button-link{
    color:#00f;
    text-decoration:underline;
}
.button-link:hover{
    cursor:pointer;
    color:#f00;
}
#modal-overlay{
    z-index:1;
    display:none;
    position:fixed;
    top:0;
    left:0;
    width:100%;
    height:120%;
    background-color:rgba(0,0,0,0.75);
}



そしてjsはこちら!

まず、全体をグレーで覆って、その上にモーダルウィンドウを表示します。
そして、imgタグに選択した画像を設定して表示すればOK!シンプルですね!

OKボタン・背景グレー・cancelボタンクリックの場合の処理は、背景グレーとモーダルウィンドウ非表示にするだけなんで基本的には全て同じなんですが、cancelクリックの時だけファイル選択クリア入れてます。

function imgSelect() {
    var file = $("#imageSelect").prop("files")[0];
                
    //画像ファイルかチェック
    if (file["type"] != "image/jpeg" && file["type"] != "image/png" && file["type"] != "image/gif") {
        alert("画像ファイルを選択してください");
        //ファイル選択クリア
        $("#imageSelect").val('');

    } else {
        var fr = new FileReader();

        fr.onload = function() {
            //背景グレーにしてモーダルウィンドウを表示
            if ($("#modal-overlay")[0]) {
                $("#modal-overlay").remove();
            }
            $("body").append('<div id="modal-overlay"></div>');
            $("#modal-overlay").fadeIn("slow");
            $("#modal-content").fadeIn("slow");
                        
            //選択した画像をimgタグに表示
            $("#preview").attr("src", fr.result);
                        
            //OKボタンまたは背景のグレーをクリックした場合
            $("#modal-ok, #modal-overlay").unbind().click(function () {                            
                //モーダルウィンドウ非表示にして、背景グレーも非表示
                $("#modal-content, #modal-overlay").fadeOut("slow", function () {
                    $("#modal-overlay").remove();
                });
            });
                        
            //cancelボタンクリックした場合
            $("#modal-cancel").unbind().click(function () {
                //モーダルウィンドウ非表示にして、背景グレーも非表示
                $("#modal-content, #modal-overlay").fadeOut("slow", function () {
                    $("#modal-overlay").remove();
                });
                //ファイル選択クリア
                $("#imageSelect").val('');
            });
        };

        fr.readAsDataURL(file);
    }
}