jquery - 缩放图像并将其居中而不剪切边框

标签 jquery css image centering

我尝试了很多不同的方法,但没有一个有效。

我有一张图片(比如说未知的高度和宽度),我希望它居中(垂直和水平)。高度和宽度由窗口大小决定,但不得超过原始高度和/或宽度。

例如,当您双击图片时,您可以查看Windows Live 照片库。这正是我所需要的,在 css/jquery 中。我不知道如何调整图像以适合页面。

感谢您的帮助。

我不知 Prop 体术语,因为英语不是我的母语。

最佳答案

如果您事先(在服务器端)知道图像的大小,最简单的方法是在渲染 HTML 时做到这一点;使用widthheight您的<img>的属性标签来设置其大小,它是 margin-leftmargin-top将其放入容器的中心。这对于最终用户来说会更好,因为在加载图像后重新调整 JavaScript 大小时,他不会看到屏幕闪烁。这是迄今为止最好的方法。

编辑:如评论中所述,如果您使用服务器端解决方案,您可能仍希望在 $(window).resize() 上使用 javascript 解决方案,以便图像保持居中如果用户更改窗口尺寸,则尺寸也正确。

--

但是,由于您的问题是针对 javascript 的,因此您需要分两步进行;首先在保持比例的情况下减小图像的高度和宽度,使其不大于窗口,然后第二次应用一些边距使其水平和垂直居中。

这是一个如何实现您想要的结果的示例,请注意,此代码显然没有经过优化,可能不应该按原样使用,我将其保留为“详细”状态使其更容易理解的方法。

HTML:

<body>
  <div id="main" style="margin: 0; padding: 0">
    <img id="yourpic" src="http://domain.com/image.png" />
  </div>
</body>

JS:

// we use the onLoad event so that your browser know the image dimension
$('#yourpic').load(function() {
    // cache your objects
    var $window = $(window);
    var $this = $(this);

    var tmp;

    // if the image has too much width reduce it, keeping its ratio
    if ($window.width() < this.width) {
        tmp = [this.width, this.height];
        $this.width($window.width());
        $this.height(tmp[1] / (tmp[0] / this.width));
    }

    // same for its height
    if ($window.height() < this.height) {
        tmp = [this.height, this.width];
        $this.height($window.height());
        $this.width(tmp[1] / (tmp[0] / this.height));
    }

    // now center it horizontally
    if ($window.width() > this.width) {
        $this.css('margin-left', ($window.width() - this.width) / 2);
    }

    // and vertically
    if ($window.height() > this.height) {
        $this.css('margin-top', ($window.height() - this.height) / 2);
    }
});

您可以在此处的示例中看到它:http://jsfiddle.net/RPCjE/2/ (chome img.onload 事件是 quite buggy 因此,如果您使用此浏览器,您可能必须在没有缓存的情况下刷新)。

关于jquery - 缩放图像并将其居中而不剪切边框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7730110/

相关文章:

javascript - 使用 JavaScript 获取当鼠标悬停在表格上时选择的列数和行数

javascript - 将 id 添加到数据表行

javascript - execCommand 的字体大小导致 Google Chrome 出现问题

java - 可点击图片

android - 在android中的拨号器上显示图片

javascript - 理论上不可能获得将要使用 Javascript 上传的文件的大小吗?

javascript - 默认情况下/在页面上时保持按下按钮

html - Div 未调整大小以适合图像

html - 调整屏幕大小时更改图像

python - 使用 Python 进行图像旋转