html - 任意大小的 img 的静态最大/最小宽度

标签 html css image

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/

相关文章:

css - 当 parent 的 div 调整大小时自动缩放子滚动 div

css - 如何在页面中间插入垂直线并将表格向左移动(css)

css - 使用 Compass 编译 - 未找到或无法读取要导入的文件

Python OpenCV 颜色跟踪

html - CSS 图像缩放和悬停居中

javascript - 如何更改宽度并保持 rtl?

html - 在 log4j 的 HTMLLayout 中获取更多信息

css - 页脚栏像 facebook - css

css - 为什么我的 SVG 图像没有填充颜色?

html - 图像路径传递到 `src` 但图像不显示。