27
26

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Facebook風プレビュー付き画像アップロードエリアの実装

Posted at

概要

Facebook風に「ファイルを選択」ボタンではなく、エリアを選択してファイルを選択。
ファイルを選択するとそこにプレビュー画像を出します。

実装

HTML

test.html
<div class="file-div">
  <div>
    <img src="">
  </div>
  <input type="file">
</div>

CSS

test.css
.file-div div {
  width: 200px;
  height: 200px;
  padding: 0;
  margin: 0 10px;
  border: dashed 4px #eee;
}
.file-div img {
  width: 100%;
  height: 100%;
}
.file-div input {
  display: none;
}

javascript

test.js
// divをクリックでinputのクリックイベントを発火させる
$(".file-div > div").click(function() {
  var evt;
  evt = document.createEvent("MouseEvents");
  evt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
  $(this).siblings("input").get(0).dispatchEvent(evt);
});

//ファイルを選択したらプレビュー用のimgに反映させる
$(".file-div > input").change(function() {
  var file, fr, input;
  input = this;
  file = $(this).prop('files')[0];
  fr = new FileReader();
  fr.onload = function() {
    return $(input).siblings("div").find("img").attr('src', fr.result);
  };
  return fr.readAsDataURL(file);
});
27
26
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
27
26

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?