如何将拖放功能添加到我已自定义为图像的文件输入 HTML 标记?

问题描述 投票:0回答:1

我目前正在使用 HTML、CSS 和 JavaScript 设计一个表单,其中包括输入类型=文件。我自定义了表单,以便输入现在使用图像,可以单击该图像来浏览和选择用户计算机中的文件。不过,我还希望它具有拖放功能。

下面是我目前拥有的代码。这段代码足以做几件事:

  1. 它用 img 标签中调用的图像替换了使用带有 type=file 的输入标签时呈现的默认“选择文件”按钮。
  2. 它使用一些 JavaScript 作为 span 标记,以向用户指示他们选择了哪个文件,或者是否未选择任何文件。

这些之所以可能是因为 CSS 用于更改输入标记中的默认行为,其中 type=file。但是,我还没有找到代码来实现拖放到我当前的解决方案。有人可以帮忙吗?

<style>
    .required-file::after {
    content: "*";
    color: red;
    }
    .custom-upload {
    display: inline-block;
    padding: 6px 12px;
    cursor: pointer;
    }
    input[type="file"] {
    display: none;
    }
    </style>
    <script>
    $(function() {
    const fileUploadElement = document.getElementById('fileUpload');
    const chosenFileElement = document.getElementById('chosen-file');
    fileUploadElement.addEventListener('change', function(){
    chosenFileElement.textContent = this.files[0].name;
    });
    });
    </script>
    <label for="fileUpload" class="custom-upload">
    <img src="/fakepath/image.png" width="100" height="100">
    </label>
    <input type="file" id="fileUpload" name="fileUpload" >
    <span class="required-file" id="chosen-file">No file chosen</span>
javascript html css drag-and-drop input-type-file
1个回答
0
投票

根据您添加拖放功能并显示所选图像的要求,我修改了您的代码以包含这些功能。下面是更新后的 HTML、CSS 和 JavaScript,无缝支持这两种功能。此设置允许用户单击自定义上传区域来选择文件或将文件拖放到其上,然后立即预览所选图像。

 $(function () {
            const fileUploadElement = document.getElementById('fileUpload');
            const chosenFileElement = document.getElementById('chosen-file');
            const customUploadLabel = document.querySelector('.custom-upload');
            const imagePreview = document.getElementById('imagePreview');

            fileUploadElement.addEventListener('change', function () {
                displayImage(this.files[0]);
            });

            // Prevent default drag behaviors
            ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
                customUploadLabel.addEventListener(eventName, preventDefaults, false);
                document.body.addEventListener(eventName, preventDefaults, false);
            });

            // Highlight drop area when item is dragged over it
            ['dragenter', 'dragover'].forEach(eventName => {
                customUploadLabel.addEventListener(eventName, highlight, false);
            });

            ['dragleave', 'drop'].forEach(eventName => {
                customUploadLabel.addEventListener(eventName, unhighlight, false);
            });

            // Handle dropped files
            customUploadLabel.addEventListener('drop', handleDrop, false);

            function preventDefaults(e) {
                e.preventDefault();
                e.stopPropagation();
            }

            function highlight(e) {
                customUploadLabel.style.borderColor = '#666'; // Change as necessary
            }

            function unhighlight(e) {
                customUploadLabel.style.borderColor = '#ccc';
            }

            function handleDrop(e) {
                var dt = e.dataTransfer;
                var files = dt.files;

                if (files.length) {
                    fileUploadElement.files = files; // This won't work in all browsers as mentioned
                    displayImage(files[0]);
                }
            }

            function displayImage(file) {
                if (file && file.type.startsWith('image/')) {
                    var reader = new FileReader();
                    reader.onload = function (e) {
                        imagePreview.src = e.target.result;
                        imagePreview.style.display = 'block';
                        chosenFileElement.textContent = file.name;
                    };
                    reader.readAsDataURL(file);
                } else {
                    chosenFileElement.textContent = 'No file chosen';
                    imagePreview.style.display = 'none';
                }
            }
        });
 .required-file::after {
            content: "*";
            color: red;
        }

        .custom-upload {
            display: inline-block;
            padding: 6px 12px;
            cursor: pointer;
            border: 2px dashed #ccc;
        }

        input[type="file"] {
            display: none;
        }

        #imagePreview {
            width: 100px;
            height: 100px;
            min-height: 100px;
            min-width: 100px;
        }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<label for="fileUpload" class="custom-upload">
    <img id="imagePreview" src="/fakepath/image.png" alt="Preview">
</label>
<input type="file" id="fileUpload" name="fileUpload">
<span class="required-file" id="chosen-file">No file chosen</span>

© www.soinside.com 2019 - 2024. All rights reserved.