图像宽度:更改父块高度后的自动和最大高度

Image width:auto and max-height after changing parent block height

本文关键字:高度 图像      更新时间:2023-09-26

请参阅chrome中的示例。我尝试用不应该超过父块的图像来实现行高动画。

为什么图像宽度只有在更改任何属性示例后才会更改?

尝试单击第一个按钮,图像高度将更新,但宽度不会。然后单击第二个按钮,不透明度将更改,图像宽度将正确设置。

<!DOCTYPE html>
<html>
<head>
    <title>Image resizing</title>
    <style>
        .header-row {
            width:900px;
            height:90px;
            margin:0 auto;
            background:#0f3a51;
            -webkit-transition: all .9s ease;
            -moz-transition: all .9s ease;
            -ms-transition: all .9s ease;
            -o-transition: all .9s ease;
            transition: all .9s ease;
        }
        .header-row img {
            display: inline;
            max-height: 100%;
            background:#ff9900;
        }
        .header-row-reduced {
            height:50px;
        }
    </style>
</head>
<body>
<div id="hr" class="header-row">
    <img id="img" src="http://upload.wikimedia.org/wikipedia/commons/thumb/1/1a/Volkswagen_Logo.png/600px-Volkswagen_Logo.png" alt="">
</div>
<button id="btn" onclick="check();">Update row height</button>
<button id="btn" onclick="changeProp();">Toggle opacity</button>
<script>
    var el = document.getElementById('hr'),
        img = document.getElementById('img');
    function check(){
        var classes = el.className.split(' '),
            hasClass = classes.indexOf('header-row-reduced');
        if(~hasClass) {
            classes.splice(hasClass,1);
        } else {
            classes.push('header-row-reduced');
        }
        el.className = classes.join(' ');
    }
    function changeProp() {
        img.style.opacity = '0.5';
    }
</script>
</body>
</html>

这是个好问题。我不知道为什么这没有像预期的那样起作用。

但你也可以通过对元素应用具有高度的规则来修复它:

.header-row-reduced, .header-row-reduced img {
        height:50px;
}

这是有效的,但我相信这并不是你想要的!

以像素为单位设置最大高度也可以解决这个问题。