返回

为 input 文件控件增加操作栏,操作栏提供放大预览、下载、删除图片等交互功能

前端

前言

在前端开发中,文件控件经常用于上传图片或其他文件。然而,原生的 input file 控件样式简单,操作不方便。因此,本文将介绍如何为 input file 文件控件添加一个操作栏,操作栏提供放大预览、下载和删除图片等交互功能,使图片上传体验更加友好。

技术实现

  1. HTML 结构

首先,我们需要在 HTML 中添加一个 input file 控件和一个操作栏。操作栏包含三个按钮:放大预览、下载图片和删除图片。

<input type="file" id="file-input" multiple>
<div id="file-operation-bar">
  <button id="preview-button">放大预览</button>
  <button id="download-button">下载图片</button>
  <button id="delete-button">删除图片</button>
</div>
  1. CSS 样式

接下来,我们需要为 input file 控件和操作栏添加 CSS 样式。

#file-input {
  display: none;
}

#file-operation-bar {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  gap: 10px;
}

#preview-button, #download-button, #delete-button {
  padding: 5px 10px;
  border: 1px solid #ccc;
  border-radius: 5px;
  background-color: #fff;
  color: #666;
  cursor: pointer;
}

#preview-button:hover, #download-button:hover, #delete-button:hover {
  background-color: #eee;
}
  1. JavaScript 交互逻辑

最后,我们需要添加 JavaScript 交互逻辑来实现放大预览、下载图片和删除图片的功能。

const fileInput = document.getElementById('file-input');
const previewButton = document.getElementById('preview-button');
const downloadButton = document.getElementById('download-button');
const deleteButton = document.getElementById('delete-button');

// 放大预览
previewButton.addEventListener('click', () => {
  const files = fileInput.files;
  if (files.length === 0) {
    alert('请先选择一张图片');
    return;
  }

  const file = files[0];
  const reader = new FileReader();
  reader.onload = () => {
    const img = new Image();
    img.src = reader.result;

    const previewModal = document.createElement('div');
    previewModal.classList.add('preview-modal');
    previewModal.appendChild(img);

    document.body.appendChild(previewModal);

    // 点击图片关闭预览框
    img.addEventListener('click', () => {
      document.body.removeChild(previewModal);
    });
  };
  reader.readAsDataURL(file);
});

// 下载图片
downloadButton.addEventListener('click', () => {
  const files = fileInput.files;
  if (files.length === 0) {
    alert('请先选择一张图片');
    return;
  }

  const file = files[0];
  const a = document.createElement('a');
  a.href = URL.createObjectURL(file);
  a.download = file.name;
  a.click();
});

// 删除图片
deleteButton.addEventListener('click', () => {
  const files = fileInput.files;
  if (files.length === 0) {
    alert('请先选择一张图片');
    return;
  }

  fileInput.value = '';
});

总结

通过以上步骤,我们就可以为 input file 文件控件添加一个操作栏,操作栏提供放大预览、下载和删除图片等交互功能,使图片上传体验更加友好。希望本博文对您有所帮助。