LoginSignup
13

More than 3 years have passed since last update.

【Rails】画像プレビュー機能の実装

Posted at

目標

ezgif.com-video-to-gif.gif

開発環境

・Ruby: 2.5.7
・Rails: 5.2.4
・Vagrant: 2.2.7
・VirtualBox: 6.1
・OS: macOS Catalina

前提

下記実装済み。

Slim導入
Bootstrap3導入
Font Awesome導入
ログイン機能実装
投稿機能実装

実装

1.ビューを編集

users/edit.html.slim
/ 追記
= f.file_field :profile_image, class: 'img_field', style: 'display:none;'
= attachment_image_tag @user, :profile_image, fallback: 'no-image.png', onClick: "$('.img_field').click()", class: 'center-block img-thumbnail img-responsive img_prev'
br

【解説】

file_fielddisplay:noneの非表示にし、クラスを付与する。

= f.file_field :profile_image, class: 'img_field', style: 'display:none;'

で付与したクラスのHTML(file_field)がクリックされたらJavaScriptの処理を実行する。

onClick: "$('.img_field').click()"

2.appliacation.scssを編集

appliacation.scss
// 追記
.img_prev:hover {
  cursor: pointer; 
  opacity: 0.7;
  transform: scale(1.01, 1.01);
}

【解説】

① 画像にマウスが乗っている時にCSSを反映させる。

.img_prev:hover {}

② マウスカーソルをポインターに変更する。

cursor: pointer; 

③ 不透明度を低くして、画像を少し白くする。

opacity: 0.7;

④ 少しだけ画像を拡大する。

transform: scale(1.01, 1.01);

3.JavaScriptファイルを作成・編集

ターミナル
$ touch app/assets/javascripts/image_preview.js
image_preview.js
$(function () {
  function readURL(input) {
    if (input.files && input.files[0]) {
      var reader = new FileReader();
      reader.onload = function (e) {
        $('.img_prev').attr('src', e.target.result);
      }
      reader.readAsDataURL(input.files[0]);
    }
  }

  $('.img_field').change(function () {
    readURL(this);
  });
});

【解説】

1.ビューを編集の② で実行する処理。

$('.img_field').change(function () {
  readURL(this);
});

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
13