php - 根据高度保持纵横比

标签 php jquery html css

这是我遇到的问题。我想保持照片的纵横比并将其放入风景 div 中。问题是我想在高度上调整图片并在宽度上进行裁剪。这是我用来适应图片的脚本,但它适合宽度而不是高度。

<script>
$(document).ready(function() {
    $('.story-small img').each(function() {
        var maxWidth = 550; // Max width for the image
        var maxHeight = 413;    // Max height for the image
        var ratio = 0;  // Used for aspect ratio
        var width = $(this).width();    // Current image width
        var height = $(this).height();  // Current image height

        // Check if the current width is larger than the max
        if(width > maxWidth){
            ratio = maxWidth / width;   // get ratio for scaling image
            $(this).css("width", maxWidth); // Set new width
            $(this).css("height", height * ratio);  // Scale height based on ratio
            height = height * ratio;    // Reset height to match scaled image
            width = width * ratio;    // Reset width to match scaled image
        }

        // Check if current height is larger than max
        if(height > maxHeight){
            ratio = maxHeight / height; // get ratio for scaling image
            $(this).css("height", maxHeight);   // Set new height
            $(this).css("width", width * ratio);    // Scale width based on ratio
            width = width * ratio;    // Reset width to match scaled image
        }
    });
});
</script>

这是一个例子:Link

所以实际上第二张图片很好,因为它适合高度,这就是我想要实现的风景图片,适合高度裁剪宽度。 提前致谢。

最佳答案

试试这个:

fiddle

CSS:

img{
max-width: 550px;
max-height:440px;
}

HTML:

<img src="http://websoftit.ro/dragdrop/emma-watson-wallpaper-1920x1200.jpg">

关于php - 根据高度保持纵横比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21159801/

相关文章:

php - MYSQL TRANSACTION 的替代品?

php - 如何在后台 PHP 执行很长的任务?

javascript - D3 动态折线图添加点

php - Ajax 正在丢失 session

javascript - JavaScript 中的 Tic Tac Toe

jquery - 设置选择索引

html - 从类中提取跨度值,VBA

html - 如何使用 CSS 在 HTML 文档中插入换行符

html - 应用相对和绝对定位时的不同边框

php - 截断一些 id 而不删除其他值 MySQL