【问题标题】:Loop Through A Function Parameter / Images Created With A `new Image()` Instance循环通过函数参数/使用`new Image()`实例创建的图像
【发布时间】:2022-08-09 15:15:55
【问题描述】:

我有一个使用new Image() 创建的图像缩略图,它基本上显示了要在提交表单之前上传的图像的缩略图。

我有处理后端上传的 PHP 验证。如果图像小于 4 MB,则图像上传在后端失败,我想使用 javascript 在特定缩略图上附加一条消息。

下面的函数在带有oninput 属性的表单中调用,并采用参数file

问题

因为我本质上是在循环file参数,所以我无法弄清楚每次如何循环new Image()实例创建的图像,所以它只在相关图像上显示错误。

非常感谢任何帮助。

function updateThumbnail(file) {
    if (file.type.startsWith(\'image/\')) {

        let 
        uploadImageWrapper = document.createElement(\'figure\'),
        thumbnailElement = new Image();
    
        // image thumbnail
        thumbnailElement.classList.add(\'drop-zone__thumb\')
        thumbnailElement.src = URL.createObjectURL(file)
    
        // appending elements
        showSelectedImages.append(uploadImageWrapper) // <figure> element
        uploadImageWrapper.append(thumbnailElement) // image thumbnail

        // error messaging for file size
        let thumbnails = document.querySelectorAll(\'.drop-zone__thumb\'),
        sizeError = `<p>Image must be bigger than 4MB</p>`

        thumbnails.forEach(img => {
            if (img.size < 4000000) {
                img.insertAdjacentHTML(\'afterend\', sizeError)
            }
        })

        console.log(img.size)
        console.log(thumbnailElement)

    }

} // end of \'updateThumbnail\' function

// ---  updateThumbnail(file) is called in the HTML with an `oninput` attribute in the form
  • 如果file 的尺寸小于要求,你为什么不直接做thumbnailElement.insertAdjacentHTML(\'afterend\', sizeError)
  • @Juraj - 那行得通。这真的让我很困惑,但为什么它没有循环就可以工作?因为图像有多个实例,我认为它必须循环遍历它们。如果您将其作为答案,我会将其标记为正确,以便您获得赏金。

标签: function loops parameters blob


【解决方案1】:

该函数处理一个图像文件并为其添加缩略图,所以为什么不在那个时候只处理该图像文件的 sizeError 。

做就是了:

if (file.size < 4000000) {
  thumbnailElement.insertAdjacentHTML('afterend', sizeError);
}

并删除 thumbnails 变量和周围的代码。

【讨论】:

    猜你喜欢
    • 2019-04-13
    • 1970-01-01
    • 2021-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多