如何在javascript中重置图像维度?(MVC)
我得到了下面的javascript函数,当您传入参数时,它将加载图片并适当调整大小。有时我不知道高度和大小,因此如何重置图像的高度(以便浏览器适当调整图像大小)和宽度,或删除高度和宽度属性,以便没有传入大小的图像不会收缩到0,0大小?希望避免使用JQuery如何在javascript中重置图像维度?(MVC),javascript,html,Javascript,Html,我得到了下面的javascript函数,当您传入参数时,它将加载图片并适当调整大小。有时我不知道高度和大小,因此如何重置图像的高度(以便浏览器适当调整图像大小)和宽度,或删除高度和宽度属性,以便没有传入大小的图像不会收缩到0,0大小?希望避免使用JQuery function LoadPicture(picture,alt,text,height,width) { _img = document.getElementById('img') _img.src = '/pic/' +
function LoadPicture(picture,alt,text,height,width)
{
_img = document.getElementById('img')
_img.src = '/pic/' + picture + '.jpg';
_img.alt = alt;
_img.title = text;
if (height+'' != '' && height>0)
_img.height = height;
else {
_img.height = null;
}
if (width+'' != '' && width > 0)
_img.width = width;
else _img.width = null;
}
将style属性上的
height
/width
属性设置为auto
,应该可以解决这个问题
function LoadPicture(picture,alt,text,height,width)
{
_img = document.getElementById('img')
_img.src = '/pic/' + picture + '.jpg';
_img.alt = alt;
_img.title = text;
if (height+'' != '' && height>0)
_img.style.height = height;
else {
_img.style.height = 'auto';
}
if (width+'' != '' && width > 0)
_img.style.width = width;
else _img.style.width = 'auto';
}
另一种方法是在加载图像时读取高度
/宽度
var imgHeight;
var imgWidth;
function findHW() {
imgHeight = this.height;
imgWidth = this.width;
return true;
}
function showImage(imgPath) {
var myImage = new Image();
myImage.name = imgPath;
myImage.onload = findHW;
myImage.src = imgPath;
}
Src:
更多阅读MDN:
旁注(作者的评论)
图像.naturalWidth
和图像.naturalHeight
始终包含图像的自然尺寸,与样式设置和缩放无关。将style属性上的高度
/宽度
属性设置为自动
,应该可以解决这个问题
function LoadPicture(picture,alt,text,height,width)
{
_img = document.getElementById('img')
_img.src = '/pic/' + picture + '.jpg';
_img.alt = alt;
_img.title = text;
if (height+'' != '' && height>0)
_img.style.height = height;
else {
_img.style.height = 'auto';
}
if (width+'' != '' && width > 0)
_img.style.width = width;
else _img.style.width = 'auto';
}
另一种方法是在加载图像时读取高度
/宽度
var imgHeight;
var imgWidth;
function findHW() {
imgHeight = this.height;
imgWidth = this.width;
return true;
}
function showImage(imgPath) {
var myImage = new Image();
myImage.name = imgPath;
myImage.onload = findHW;
myImage.src = imgPath;
}
Src:
更多阅读MDN:
旁注(作者的评论)
图像.naturalWidth
和图像.naturalHeight
始终包含图像的自然尺寸,与样式和缩放无关。您可以删除内联样式,因此默认样式将“生效”:
您可以删除内联样式,因此默认样式将“生效”:
你的意思是通过从图像中读取来动态获取它?你的意思是通过从图像中读取来动态获取它?@LGSon,看看
myImage.naturalWidth
和myImage.naturalHeight
。它们总是包含图像的自然维度,与样式和缩放无关。@Thomas更新了我的答案info@LGSon,查看myImage.naturalWidth
和myImage.naturalHeight
。它们总是包含图像的自然尺寸,与样式和缩放无关。@Thomas用这一信息更新了我的答案。另一种方法是使用LGSon建议的样式属性。然后可以使用_img.style.height=”“删除高度。另一种方法是使用类似LGSon建议的样式属性。然后可以使用_img.style.height=”“删除高度