そこで、まずはそのダイアログを隠してしまい、別のボタンをクリックしたときのイベント内部で呼び出すことにします。仮のボタンを作ってしまい、それを加工するということですね。
今回は好きな画像イメージを表示するソースです。縦長と横長の写真が見栄え良く並ぶように、画像のサイズは適当に調整していますが、実際には画像ファイルであるかといった判定が必要になると思います。
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8" />
<title>jQuery File Dialog</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<style>
#file_dialog_field{
height: 30px;
width: 100%;
margin-bottom: 20px;
}
#file_button{
margin-left: 2px;
width: 140px;
font-size: 14px;
font-family: Verdana, sans-serif;
border-radius: 15px;
background-color: rgba(207,247,94,0.8);
}
#file_text{
width: 160px;
background-color: rgba(207,247,94,0.2);
}
#file_show_area img{
margin-right: 10px;
margin-bottom: 10px;
}
</style>
</head>
<body>
<!-- Not show file dialog. This is called in jQuery button function. -->
<input id="file_dialog" style="display: none;" type="file">
<div id="file_dialog_field">
<input id="file_text" type="text" readonly="readonly" placeholder="Select your image"></input>
<button id="file_button">Open your file</button>
</div>
<div id="file_show_area"></div>
<script>
$(function () {
$('#file_button,#file_text').click(function(){
$('#file_dialog').click();
});
$('#file_dialog').change(function(){
var file = $('#file_dialog')[0].files[0];
var title = file.name;
$('#file_text').val(title);
var reader = new FileReader();
reader.readAsDataURL(file);
//at the moment reader is ready
reader.onload = function(e) {
var img = new Image();
img.src = reader.result;
//ignore resizing small images.
if (!(img.width < 150)){
//Get pictures appear well-balanced.
if (img.width > img.height){
img.width = 300;
}else{
img.height = 240;
}
}
$('#file_show_area').append(img);
}
});
});
</script>
</body>
</html>
0 件のコメント:
コメントを投稿