Я пытаюсь изменить размер изображения, но не увеличивать его до его первоначального размера. Я также хочу, чтобы центр изображения находился внутри его контейнера. Это лучший способ сделать это, как это иногда кажется немного отрывистым?изменение размера изображения с соотношением сторон
Я вынул ссылку 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>