我无法使用 JS 代码设置上传的 width/height

I can not set width/height of uploaded with with JS code

在 Laravel 8/tailwindcss 2/Alpinejs 2.8 应用程序中,当显示当前图像时我有一个表单,并且 新图像 1) 可以通过预览选择和 2) 通过带有 axios 的 Js 代码保存 请求 3) 成功上传后,当前图像将替换为新的预览图像 我有一个问题,当当前图像有大尺寸然后新上传的图像看起来坏了。 我尝试用 js 代码设置大小来修复它,以在新上传文件的表单大小上显示图像:

window.axios.post('/admin/settings/app_big_logo/images/upload', mageUploadData).then((response) => {
    let img_app_big_logo = document.querySelector("#img_app_big_logo")  // show uploaded image @endsection the form
    if (img_app_big_logo) {
        // set new uploaded image
        img_app_big_logo.src = response.data.settingsItemImgProps.image_url + ( '?dt=' + Math.floor(Date.now() / 1000) )

        console.log('document.querySelector("#img_preview_app_big_logo").width::')
        console.log(document.querySelector("#img_preview_app_big_logo").width)
        // I got width/height of new uploaded image - in console I see small values of image

        // But after assigning width/height of preview image
        img_app_big_logo.width= document.querySelector("#img_preview_app_big_logo").width //+ "px"
        img_app_big_logo.height= document.querySelector("#img_preview_app_big_logo").height //+ "px"
        
        // I check and see prior  width/height of PRIOR BIG image - so new uploaded image looks broken
        console.log('img_app_big_logo.width::')
        console.log(img_app_big_logo.width)
        console.log('img_app_big_logo.height::')
        console.log(img_app_big_logo.height)
        ...
    }
}).catch((error) => {
    console.error(error)

});

为什么会出错,如何解决?

谢谢!

听起来您在 html 图像元素上设置了图像属性。在更新图像对象的宽度和高度时,您需要对属性执行相同的操作。

不管怎样,这里有几个选项:

1。使用 image.onload 事件

重置 width/height 属性

您需要删除 img 标签上的所有图像 width/height 属性,因为这会影响浏览器呈现新图像的方式。然后,您可以在 image.onload 事件触发后再次设置它们。

if (img_app_big_logo) {
    // Set uploaded image path as src
    img_app_big_logo.src = response.data.settingsItemImgProps.image_url + ('?dt=' + Math.floor(Date.now() / 1000))

    // Remove old width/height attributes
    myImage.removeAttribute('width')
    myImage.removeAttribute('height')

    // Update after load event to make sure we have new img data
    img_app_big_logo.onload = () => {
        // Set new width/height attributes
        myImage.setAttribute('width', img_app_big_logo.width)
        myImage.setAttribute('height', img_app_big_logo.height)
    }
}

2。插入一个新的 img 元素并删除旧的

可能是更清洁的解决方案。在这里,我们创建一个新的 img 元素,将我们可能需要的任何 properties/attributes 复制到它。

if (img_app_big_logo) {
    // Create a new img element and set src
    var newImg = document.createElement("img");
    newImg.src = response.data.settingsItemImgProps.image_url + ('?dt=' + Math.floor(Date.now() / 1000));

    // Here we might set id, classes etc
    newImg.id = img_app_big_logo.classList
    newImg.classList = img_app_big_logo.classList

    // Now we append the new img to the same container and remove the old one
    img_app_big_logo.parentNode.appendChild(newImg)
    img_app_big_logo.remove()
}

两种选择。希望有帮助