我如何将 jQuery 中的图像调整为一致的纵横比。例如设置最大高度并正确调整宽度。谢谢。
最佳答案
这是一个有用的函数,可以满足您的需求:
jQuery.fn.fitToParent = function()
{
this.each(function()
{
var width = $(this).width();
var height = $(this).height();
var parentWidth = $(this).parent().width();
var parentHeight = $(this).parent().height();
if(width/parentWidth < height/parentHeight) {
newWidth = parentWidth;
newHeight = newWidth/width*height;
}
else {
newHeight = parentHeight;
newWidth = newHeight/height*width;
}
var margin_top = (parentHeight - newHeight) / 2;
var margin_left = (parentWidth - newWidth ) / 2;
$(this).css({'margin-top' :margin_top + 'px',
'margin-left':margin_left + 'px',
'height' :newHeight + 'px',
'width' :newWidth + 'px'});
});
};
基本上,它会抓取一个元素,将其置于父元素的中心,然后将其拉伸(stretch)以适应父元素的背景不可见,同时保持宽高比。
话又说回来,这可能不是你想要做的。
关于javascript - jQuery 调整大小以适应纵横比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1682495/