2011-10-11 51 views
1

我试过很多不同的东西,但都没有工作。将图像放大并居中放大而不削减边框

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

作为一个例子,你可以看看Windows Live照片库,当你双击图片。这正是我需要的,在CSS/jQuery中。我不知道如何根据需要调整图片以适合页面。

感谢您的任何帮助。

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

回答

3

如果您事先知道您的图片大小(在服务器端),最简单的方法是在呈现HTML时执行此操作;使用<img>标记的widthheight属性来设置其大小,并使用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/(丁目img.onload事件是quite buggy所以如果你使用这个浏览器,你可能必须刷新而不需要缓存)。

+0

好图片,那是哪里? – magritte

+1

不知道,我从imgur的主页上看到了第一个大的图片:http://imgur.com/gallery/fWoCV – Lepidosteus

+0

但是,如果我在将图像发送给浏览器之前使用PHP呈现图像,那么如果窗口被调整大小,PHP需要重新渲染图片并可能会减慢用户体验,您怎么看?漂亮的图片;)...并感谢代码,我会玩这个。 –