Javascript 我不能用JS代码设置上传的宽度/高度
在Laravel8/tailwindcss 2/Alpinejs 2.8应用程序中,当显示当前图像并 新图像1)可以通过预览选择,2)通过axios的Js代码保存 请求3)成功上载后,当前图像将替换为新的预览图像 我有一个问题,当当前的图像有大尺寸,然后新上传的图像看起来破了。 我尝试用js代码将大小设置为新上传文件的表单大小上的图像来修复它:Javascript 我不能用JS代码设置上传的宽度/高度,javascript,alpine.js,Javascript,Alpine.js,在Laravel8/tailwindcss 2/Alpinejs 2.8应用程序中,当显示当前图像并 新图像1)可以通过预览选择,2)通过axios的Js代码保存 请求3)成功上载后,当前图像将替换为新的预览图像 我有一个问题,当当前的图像有大尺寸,然后新上传的图像看起来破了。 我尝试用js代码将大小设置为新上传文件的表单大小上的图像来修复它: window.axios.post('/admin/settings/app_big_logo/images/upload', mageUploadDa
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事件重置宽度/高度属性 您需要删除img标记上的任何图像宽度/高度属性,因为这将影响浏览器渲染新图像的方式。然后,您可以在触发
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元件
可能是一种更清洁的解决方案。在这里,我们创建一个新的img
元素,将可能需要的任何属性/属性复制到该元素中
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()
}
两种选择。希望这里有一些有用的提示:您使用了Java标记,但询问了JavaScript。