gpt4 book ai didi

jquery - 按纵横比调整图像大小

转载 作者:行者123 更新时间:2023-11-28 18:51:01 25 4
gpt4 key购买 nike

我正在尝试调整图像大小但不将其增加到超过其原始大小 - 我还想将图像置于其容器的中心。这是最好的方法,因为它有时看起来有点生涩?

我把jquery js链接去掉了

<html>
<head>
<style type="text/css">
.container {
width: 100%;
height: 100%;
background: #444;
}
</style>
</head>

<body>
<div class="container">
<img src="D:\large.png" />
</div>
</body>

<script>
var $orig_width=0;
var $orig_height=0;
var width;
var height;
var $img;

$(window).load(function() {
$img = $('.container').find('img');
$orig_width=$img.width();
$orig_height=$img.height();
resize();
});

function resize() {
var width=$img.width();
var height=$img.height();
var parentWidth = $img.parent().width();
var parentHeight = $img.parent().height();

newWidth = parentWidth;
newHeight = newWidth/width*height;

if (newHeight>$orig_height) newHeight=$orig_height;
if (newWidth>$orig_width) newWidth=$orig_width;

margin_top = (parentHeight - newHeight) / 2;
margin_left = ((parentWidth - newWidth ) / 2);

$img.css({'margin-top' :margin_top + 'px',
'margin-left':margin_left + 'px',
'height' :newHeight + 'px',
'width' :newWidth + 'px'});
}

$(window).resize(function() {
resize();
})

</script>

</html>

最佳答案

您只需使用表格作为容器。因为你很容易在表格中对齐它。将固定宽度和高度设置为属性将带来固定尺寸图像的解决方案。

关于jquery - 按纵横比调整图像大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9275279/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com