缩放图像并将其居中而不剪切边框
我尝试了很多不同的方法,但没有一个有效。
我有一张图片(比如说未知的高度和宽度),我希望它居中(垂直和水平)。高度和宽度由窗口尺寸决定,但不得超过原始高度和/或宽度。
例如,当您双击图片时,您可以查看Windows Live 照片库。这正是我所需要的,在 css/jquery 中。我不知道如何调整图像以适合页面中的需要。
感谢您的任何帮助。
我不知道具体术语,因为英语不是我的母语。
I've tried many different things but none is working.
I have a picture (let say unknown height and width) and I want it centered (vertically and horizontally). The height and width is determined by the window size, but must not be more than the original height and/or width.
As an exemple, you can look at Windows Live Photo Gallery, when you double click on a picture. This is exactly what I need, in css/jquery. I don't know how to adjust the image to fit as I want in the page.
Thanks for any help.
I don't know the specific term since english is not my native language.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您事先(在服务器端)知道图像的大小,最简单的方法是在渲染 HTML 时知道;使用
标记的
width
和height
属性来设置其大小,并且它是margin-left
和margin-top
将其置于容器中心。这对于最终用户来说会更好,因为在加载图像后重新调整 JavaScript 大小时,他不会看到屏幕闪烁。这是迄今为止最好的方法。编辑:如评论中所述,如果您使用服务器端解决方案,您可能仍希望在 $(window).resize() 上使用 javascript 解决方案,以便图像保持居中且大小合适如果用户更改窗口的尺寸。
--
但是,由于您的问题是针对 javascript 的,因此您需要分两步进行;首先减小图像的高度和宽度,使其不大于窗口,同时保持比例,然后第二次应用一些边距使其水平和垂直居中。
这是一个如何实现您想要的示例,请注意,此代码显然没有优化,可能不应该按原样使用,我将其保留为“详细”方式以保持这样比较容易理解。
HTML:
JS:
您可以在此处的示例中看到它: http://jsfiddle.net/RPCjE/2/ (chome img.onload 事件有很多错误所以如果你使用此浏览器时,您可能需要在没有缓存的情况下刷新)。
If you know your image's size before hand (on the server side), the easiest way is to do it when rendering the HTML; use the
width
andheight
attribute of your<img>
tag to set its size, and it'smargin-left
andmargin-top
to center it into a container. This will make it a lot better for the end user as he won't see the screen flicker when re-sized javascript side after the image is loaded. This is by far the best way to do this.Edit: as stated in the comments, if you use the server side solution you might want to still use a javascript solution on $(window).resize(), so that the image stays centered and properly sized if the user change the window's dimensions.
--
However, since your question is for javascript, you need to work in two steps; first reduce the image height and width so as not to be larger than the window while keeping ratio, then in a second time apply some margin to center it both horizontally and vertically.
Here is an example of how you could achieve what you want, note that this code is clearly not optimized and probably shouldn't be used as-is, I leave it in its "verbose" way to keep it easier to understand.
The HTML:
The JS:
You can see it in example here: http://jsfiddle.net/RPCjE/2/ (chome img.onload event is quite buggy so if you are using this browser you might have to refresh with no cache).