javascript 使用 jQuery 调整图像大小和居中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3987644/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Resize and Center image with jQuery
提问by Marco
Looks like I haven't explained myself well. I do apologize for that.
看来我没有很好地解释自己。对此我深表歉意。
I have edited this question to make it more clear.
我编辑了这个问题以使其更清楚。
The scenario
场景
We have a website that doesn't host the images. What it does is a reference to an image in other server.
我们有一个不托管图像的网站。它的作用是引用其他服务器中的图像。
The plan
计划
- Resize images keeping proportions.
- Center resized images.
- Flexible so it can fit in several sizes.
- 调整图像大小保持比例。
- 居中调整大小的图像。
- 灵活,因此它可以适应多种尺寸。
The bug
错误
My code works as intended, however there is a Bug that only happens sometimes.
我的代码按预期工作,但是有一个只偶尔发生的错误。
If you go to the search page of the website, and swap between page 1, 2, 3 and 4 a couple of times, you will notice that sometimes the images are good… other times they appear aligned left, and do not take up the full container area.
如果你进入网站的搜索页面,在第 1、2、3、4 页之间切换几次,你会发现有时图像很好……有时它们看起来左对齐,而不是占据全集装箱区。
The links
链接
The full website(in beta)
完整的网站(测试版)
The jQuery plugin that helped me(jThumb)
帮助我的 jQuery 插件(jThumb)
The plan (detailed version)
计划(详细版)
Let's say that the image is 600x400 pixels (remember they are not hosted on this server), and with jQuery and CSS, I want to resize the image (keeping proportions) in to a container of 310x200 pixels.
假设图像是 600x400 像素(记住它们不是托管在此服务器上),并且使用 jQuery 和 CSS,我想将图像大小(保持比例)调整为 310x200 像素的容器。
The other challenge is to center the image.
另一个挑战是使图像居中。
All this has to be flexible because there are several different containers sizes in the website.
所有这些都必须灵活,因为网站中有几种不同的容器大小。
What I have done so far (you can find this in the link above)
到目前为止我做了什么(你可以在上面的链接中找到这个)
To resize the image I'm doing:
要调整我正在做的图像大小:
var img = new Image();
img.src = $(this).attr("src");
var width = $(this).css('width');
var height = $(this).css('height');
var photoAspectRatio = img.width / img.height;
var canvasAspectRatio = width.replace("px", "") / height.replace("px", "");
if (photoAspectRatio < canvasAspectRatio) {
$(this).css('width', width);
$(this).css('height', 'auto');
var intHeight = height.replace("px", ""); //tirar o PX
$(this).css('marginTop', (-Math.floor(intHeight / 2)));
}
else {
$(this).css('width', 'auto');
$(this).css('height', height);
}
$(this).wrap('<div class="thumb-img" style="width:' + width + ' ;height:' + height + ';"><div class="thumb-inner">' + '</div></div>');
To center the image I'm doing:
为了使我正在做的图像居中:
jQuery(this).css('position','absolute');
jQuery(this).left( '-' + ( parseInt( $(this).width() ) / 2 ) + 'px' );
jQuery(this).top( '-' + ( parseInt( $(this).height() ) / 2 ) + 'px' );
jQuery(this).css('margin-left', '50%' );
jQuery(this).css('margin-top', '50%');
回答by Scott S
There's a far simpler solution to determine how to resize and position the image. It will work with all image and container sizes.
有一个更简单的解决方案来确定如何调整图像的大小和位置。它将适用于所有图像和容器大小。
var canvasWidth = parseInt(width);
var canvasHeight = parseInt(height);
var minRatio = Math.min(canvasWidth / img.width, canvasHeight / img.height);
var newImgWidth = minRatio * img.width;
var newImgHeight = minRatio * img.height;
var newImgX = (canvasWidth - newImgWidth) / 2;
var newImgY = (canvasHeight - newImgHeight) / 2;
Now just position the image using newImgX, newImgY, and resize it to newImgWidth, newImageHeight.
现在只需使用 newImgX、newImgY 定位图像,并将其调整为 newImgWidth、newImageHeight。
回答by Ben Lee
This is probably a race condition. You are setting the img src and then immediately trying to get its width and height attributes. But there is no guarantee that the web browser has downloaded the image or pulled it from the browser cache yet, and if it hasn't, your code will lead to unexpected results.
这可能是一种竞争条件。您正在设置 img src,然后立即尝试获取其宽度和高度属性。但是不能保证 Web 浏览器已经下载图像或从浏览器缓存中提取图像,如果还没有,您的代码将导致意外结果。
You need to do something like this:
你需要做这样的事情:
var img = new Image();
var $thumb = $(this);
img.load(function() {
/* .....[image calculation and resize logic]..... */
});
img.src = $thumb.attr("src");
Note that the order of the above statements is very important -- you must attach the img.load event handler first, then assign the img.src second. If you do it in the other order, you will end up with an opposite race condition (the image may already be loaded after the img.src assignment, in which case the event handler will not be called in all browsers -- by setting the event handler first you ensure that it will be called after the img.src assignment even if the image is already loaded).
请注意,上述语句的顺序是非常重要的-你必须附上img.load事件处理程序首先,然后分配img.src第二。如果您以其他顺序执行此操作,则最终会出现相反的竞争条件(图像可能已在 img.src 分配后加载,在这种情况下,不会在所有浏览器中调用事件处理程序——通过设置事件处理程序首先确保它会在 img.src 分配之后被调用,即使图像已经加载)。
Also, note the $thumb definition at the top. This is because "this", inside the img.load function, will be a reference to the new "img", not the thumbnail element. So your logic will have to reference "$thumb" for the DOM element and "this" (or "img") for the in-memory image.
另外,请注意顶部的 $thumb 定义。这是因为 img.load 函数中的“this”将是对新“img”的引用,而不是缩略图元素。因此,您的逻辑必须为 DOM 元素引用“$thumb”,为内存中的图像引用“this”(或“img”)。
Also, for the actual logic take a look at the answer "Scott S" provided above. His suggestion looks simpler than what you have.
此外,对于实际逻辑,请查看上面提供的答案“Scott S”。他的建议看起来比你的要简单。
回答by munge83
This script will shrinks, and align image depending of their orientation. Image is rounded with div ho has fixed width and hight, and also a style set to overflow:hidden. The script actual recognize the image orientation and ad to image a margin-left or margin-top in minus atribute to style depending of a image vertical or horizontal orientation.
此脚本将缩小,并根据图像的方向对齐图像。图像四舍五入 div ho 具有固定的宽度和高度,还有一个样式设置为溢出:隐藏。该脚本实际识别图像方向,并根据图像的垂直或水平方向在减去属性的样式中对 margin-left 或 margin-top 进行图像处理。
CSS:
CSS:
<style type="text/css">
.thumb {
width:160px;
height:160px;
overflow:hidden;
}
</style>
jquery with javascript:
jquery 与 javascript:
window.onload = function() {
var images = $(".image_center");
for(i=0; i<images.length; i++)
images[i].onload = centerImage(images[i]);
function centerImage(img) {
if (img.width > img.height ) {
var y = 160;
var x = img.width/img.height*y;
var marx = (x-y)/2;
img.style.height = y+"px";
img.style.marginLeft = -(marx) + "px";
}
if (img.width < img.height ) {
var x = 160;
var y = img.height/img.width*x;
var mary = (y-x)/2;
img.style.width = x+"px";
img.style.marginTop = -(mary) + "px";
}
}
}
HTML:
HTML:
<div class="thumb"><img class="image_center" src="sa.jpg" alt="#" /></div>
<div class="thumb"><img class="image_center" src="sb.jpg" alt="#" /></div>
You can see demo here: Link
您可以在此处查看演示:链接
回答by JamieL
Another useful plugin which achieves this is jQuery Center Imagewhich supports two modes. One to fill the entire space by cropping and resizing the image and another which emulates max-width/max-height to resize to fit within the space.
实现此目的的另一个有用插件是jQuery Center Image,它支持两种模式。一个通过裁剪和调整图像大小来填充整个空间,另一个模拟最大宽度/最大高度以调整大小以适应空间。
回答by Oskar Austegard
It's not clear from your question, but I'm assuming one your issues is the left-align of the images in the table at the bottom half of your front page at http://www.algarvehouses.com.
您的问题并不清楚,但我假设您的问题之一是http://www.algarvehouses.com 上首页下半部分表格中的图像左对齐。
The issue here is not your jQuery code, rather it is your CSS.
这里的问题不是您的 jQuery 代码,而是您的 CSS。
add a text-align: center to your thumb-inner class. Then make sure that rule is loaded AFTER the "table.dlRandom img, ..." rule - or remove the display:block from that rule. That should center those images.
将 text-align: center 添加到您的拇指内部类。然后确保在“table.dlRandom img, ...”规则之后加载该规则 - 或从该规则中删除 display:block 。那应该将这些图像居中。
Generally though - to scale the image, your logic looks correct up to the point of the div. Don't quite understand that logic. You don't need to set the auto size though, just restrain the dimension that is required.
一般来说 - 要缩放图像,您的逻辑在 div 点之前看起来是正确的。不太明白这个逻辑。不过,您不需要设置自动大小,只需限制所需的尺寸即可。
One tangential tip - in the code above you reference $(this) no less than 16 times. Do this at the top of the function, and use it from there on:
一个切线提示 - 在上面的代码中,您引用 $(this) 不少于 16 次。在函数的顶部执行此操作,然后从那里开始使用它:
var $this = $(this);
回答by Fatih Acet
I really didn't get your question but this maybe be help you.
我真的没有得到你的问题,但这可能会帮助你。
function resizer(imgCls, maxWidth, maxHeight) {
var img = $('img'), imgWidth, imgHeight;
img.each(function () {
imgWidth = this.width;
imgHeight = this.height;
if (imgWidth > maxWidth || imgHeight > maxHeight) {
var widthFact = maxWidth / imgWidth;
var heightFact = maxHeight / imgHeight;
var chooseFact = (widthFact > heightFact) ? heightFact : widthFact;
imgWidth = imgWidth * chooseFact;
imgHeight = imgHeight * chooseFact;
}
})
}
this code gets the images matches the provided className and looks your arguments. pass maxWidth to your maxWidth value such as 300 px, and pass maxHeight to your images maxHeight such as 300.
此代码获取与提供的 className 匹配的图像并查看您的参数。将 maxWidth 传递给您的 maxWidth 值,例如 300 px,并将 maxHeight 传递给您的图像 maxHeight,例如 300。
then the function will loop for every image and checks its width and height. If its width or height is larger than your max values then it will be resized by keeping the aspect ratio.
然后该函数将为每个图像循环并检查其宽度和高度。如果它的宽度或高度大于您的最大值,那么它将通过保持纵横比来调整大小。
Please let you free to ask more question about the issue and please be more clear.
请让您自由提出有关该问题的更多问题,并请更清楚。

