GD bbPress Attachmentsプラグインのドラッグ&ドロップで画像をプレビューするようにしてみました。
画像プレビューの詳細については下記記事をご覧ください。
まずはHTMLにファイルをドロップするエリアを作ります。ここではファイル選択ボタンの上にdivタグを置いてみました。
<div id="a1"></div>
<input type="file" size="40" name="d4p_attachment[]"><br/>
次にスタイルを設定します。WordPressのメディアのように装飾してみました。
#a1 {
height: 50px;
background-color: #f1f1f1;
border: dashed 2px #b1b1b1;
margin-bottom: 15px;
}
.a2 {
border-color: #000 !important;
}
最後にスクリプトです。
(function($) {
$(document).on('change', 'input[name="d4p_attachment[]"]', function() {
let x = $(this);
if (x.next()[0].localName == 'img') {
x.next().remove();
}
if (x[0].files.length) {
let f = x[0].files[0];
if (f.type.match('image')) {
let r = new FileReader();
r.addEventListener('load', function(e) {
let m = $('<img>').attr('src', e.target.result);
x.after(m[0]);
});
r.readAsDataURL(f);
}
}
});
$('#a1').on('dragover', function(e) {
e.preventDefault();
$(this).addClass('a2');
});
$('#a1').on('dragleave', function(e) {
$(this).removeClass('a2');
});
$('#a1').on('drop', function(e) {
e.preventDefault();
$(this).removeClass('a2');
$('input[name="d4p_attachment[]"]:first')[0].files = e.originalEvent.dataTransfer.files;
$('input[name="d4p_attachment[]"]:first').change();
});
})(jQuery);
実際に動かすと下の画像のようにドラッグ中はボーダーが黒色になり画像の右下のテキストが「+コピー」から「→移動」に変わります。(Google Chromeの場合)

