回答編集履歴

2

調整

2024/07/08 08:59

投稿

yambejp
yambejp

スコア115896

test CHANGED
@@ -54,15 +54,12 @@
54
54
  });
55
55
  document.addEventListener('change',({target})=>{
56
56
  if(target.matches('[type=file]')){
57
- var file = target.files[0];
57
+ const file = target.files[0];
58
- const type=file.type;
59
- const filename=file.name;
60
- const blob=new Blob([file],{type:type});
61
58
  image_preview.removeAttribute('hidden');
62
59
  const image=document.querySelector('#image_preview img');
63
- image.src = URL.createObjectURL(blob);
60
+ image.src = URL.createObjectURL(file);
64
61
  const caption=document.querySelector('#image_preview figcaption');
65
- caption.textContent=filename;
62
+ caption.textContent=file.name;
66
63
  btn.setAttribute('hidden',1);
67
64
  }
68
65
  });
@@ -92,3 +89,4 @@
92
89
  </figure>
93
90
  </div>
94
91
  ```
92
+ ※Lhankor_Mhyさんの指摘を反映済み

1

調整

2024/07/08 02:54

投稿

yambejp
yambejp

スコア115896

test CHANGED
@@ -41,3 +41,54 @@
41
41
  </figure>
42
42
  </div>
43
43
  ```
44
+
45
+ # 調整
46
+ > 「ファイルを選択」ボタンの横に「選択されていません」の文言が表示されている状態が初期状態なので、その文言だけを非表示にしたいという意味でした。
47
+
48
+ これはHTMLの仕様なのでいやなら別にボタンをつくることです
49
+ ```html
50
+ <script>
51
+ window.addEventListener('DOMContentLoaded', ()=>{
52
+ image_preview.setAttribute('hidden',1);
53
+ select_image.setAttribute('hidden',1);
54
+ });
55
+ document.addEventListener('change',({target})=>{
56
+ if(target.matches('[type=file]')){
57
+ var file = target.files[0];
58
+ const type=file.type;
59
+ const filename=file.name;
60
+ const blob=new Blob([file],{type:type});
61
+ image_preview.removeAttribute('hidden');
62
+ const image=document.querySelector('#image_preview img');
63
+ image.src = URL.createObjectURL(blob);
64
+ const caption=document.querySelector('#image_preview figcaption');
65
+ caption.textContent=filename;
66
+ btn.setAttribute('hidden',1);
67
+ }
68
+ });
69
+ document.addEventListener('click',({target})=>{
70
+ if(target.matches('#image_preview img')){
71
+ select_image.click();
72
+ }
73
+ if(target.matches('#btn')){
74
+ select_image.click();
75
+ }
76
+ if(target.matches('#remove_image')){
77
+ select_image.value='';
78
+ image_preview.setAttribute('hidden',1);
79
+ btn.removeAttribute('hidden');
80
+ }
81
+ });
82
+ </script>
83
+ <div>
84
+ <p>
85
+ <input type="file" name="image" id="select_image" accept="image/*">
86
+ <input type="button" value="ファイル選択" id="btn">
87
+ </p>
88
+ <figure id="image_preview">
89
+ <img src="" >
90
+ <figcaption></figcaption>
91
+ <button name="rmImage" id="remove_image" type="button">リセット</button>
92
+ </figure>
93
+ </div>
94
+ ```