Mar*_*rco 7 javascript jquery resize image jquery-plugins
看起来我没有很好地解释自己.我为此道歉.
我已编辑此问题以使其更清晰.
我们有一个不托管图片的网站.它的作用是对其他服务器中的图像的引用.
我的代码按预期工作,但有时会出现一个Bug.
如果你去网站的搜索页面,并在第1,第2,第3和第4页之间交换几次,你会注意到有时图像是好的...有时候它们看起来是左对齐的,并且不会占用满容器区.
完整的网站(测试版)
帮助我的jQuery插件(jThumb)
假设图像是600x400像素(记住它们不在此服务器上托管),并且使用jQuery和CSS,我想将图像(保持比例)调整为310x200像素的容器.
另一个挑战是使图像居中.
所有这一切都必须灵活,因为网站上有几种不同的容器尺寸.
为了调整我正在做的图像的大小:
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>');
Run Code Online (Sandbox Code Playgroud)
为了使我正在做的图像居中:
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%');
Run Code Online (Sandbox Code Playgroud)
有一个更简单的解决方案来确定如何调整图像大小和位置.它适用于所有图像和容器尺寸.
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;
Run Code Online (Sandbox Code Playgroud)
现在只需使用newImgX,newImgY定位图像,并将其大小调整为newImgWidth,newImageHeight.
从您的问题中尚不清楚,但我假设您的问题之一是首页下半部分表格中图像的左对齐,网址为http://www.algarvehouses.com。
这里的问题不是你的 jQuery 代码,而是你的 CSS。
添加一个 text-align: center 到你的拇指内部类。然后确保在“table.dlRandom img, ...”规则之后加载该规则 - 或从该规则中删除 display:block。这应该将这些图像居中。
一般来说,为了缩放图像,您的逻辑在 div 点之前看起来都是正确的。不太明白这个逻辑。不过,您不需要设置自动尺寸,只需限制所需的尺寸即可。
一个切题提示 - 在上面的代码中,您引用 $(this) 的次数不少于 16 次。在函数的顶部执行此操作,然后从那里使用它:
var $this = $(this);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
17575 次 |
| 最近记录: |