【问题标题】:Zoom and center an image without cutting the borders缩放和居中图像而不切割边框
【发布时间】:2011-12-05 12:26:09
【问题描述】:

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

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

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

感谢您的帮助。

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

【问题讨论】:

    标签: jquery css image centering


    【解决方案1】:

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

    编辑:如 cmets 所述,如果您使用服务器端解决方案,您可能仍希望在 $(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,因此如果您使用此浏览器,您可能需要在没有缓存的情况下刷新)。

    【讨论】:

    • 不知道,我从imgur的主页上拿了第一个大的:imgur.com/gallery/fWoCV
    • 但是如果我在发送到浏览器之前使用PHP渲染图像,如果窗口被调整大小,PHP需要重新渲染图片,可能会降低用户体验,你怎么看?漂亮的图片;)...感谢您的代码,我会解决这个问题。
    • @JeremyDicaire:使用 php 渲染它,并在需要时添加一个 $(window).resize() 处理程序以在 javascript 中调整大小。您可以获得完美的渲染,没有闪烁,并且在调整大小的情况下,它会根据需要进行调整。
    • @Lepidosteus:抱歉,我不知道如何使用 $(window).resize 调整图像大小...图像不会变大/变小...你能给我一个提示吗请? (我已经删除了这部分的 $('#yourpic').load 事件)THX
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-26
    相关资源
    最近更新 更多