max-
和 min-width
<img>
上的属性标签非常有用,尤其是最大宽度,它可以防止 img 拉伸(stretch)超过其原始尺寸。
现在,当您使用特定图像时,这很容易,因此您可以将其设置为与图像大小相同。但是,如果您想将其应用于一般图像,例如用户上传的图像,该怎么办? (所以您不知道尺寸是多少)换句话说,对于任意图像,将最大/最小宽度设置为图像的确切尺寸。
最佳答案
这应该能做到...
<html>
<script src="http://code.jquery.com/jquery-1.11.1.min.js">
</script>
...
<div id="img-container"></div>
...
</html>
<script>
function loadImage(imgSrc) {
var newImg = new Image();
newImg.onload = function() {
var height = newImg.height;
var width = newImg.width;
$(newImg).css({
'max-width':width,
'max-height':height
});
$("#img-container").append(newImg);
}
newImg.src = imgSrc; // this must be done AFTER setting onload
}
loadImage('youimage.jpg');
</script>
您还可以使用服务器端代码来获取图像大小。
关于html - 任意大小的 img 的静态最大/最小宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24608555/