【根据元素或设备宽动态设定图片高度】

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>img Adaptive</title>
    <style>
        body {
            margin: 0;
            padding: 0;
        }
        .img-box {
            display: flex;
            justify-content: space-around;
            flex-wrap: wrap; /*这里给它自动换行*/
        }
        .img-box img {
            width: calc(100%/3 - 2px); /*三列一行,左右间距2px*/
        }
    </style>
</head>
<body>
    <div class="img-box">
        <img src="./timg.jpg" alt="">
        <img src="./timg.jpg" alt="">
        <img src="./timg.jpg" alt="">
        <img src="./timg.jpg" alt="">
        <img src="./timg.jpg" alt="">
    </div>
</body>
<script>
    // 这里是取body的宽为基准来设置图片的高度
    var deviceWidth = document.getElementsByTagName('body')[0].offsetWidth;
    var height = 'height:' + (deviceWidth/3 - 2) + 'px'; // 这里设置为正方形,所以高度等于图片的宽
    /**
     *
     * @param selector:要设置高度元素的css选择器
     * @param css:样式字符串(属性名:样式)
     * @param style_id:<style>标签的id
     */
    function adaptive_img_height(selector, css, style_id) {
        // 如果一直动态加载样式标签不友好,所以这里先删除原有的。
        var oldStyle = document.getElementById(style_id);
        if (oldStyle) {
            oldStyle.remove();
        }
        // 创建<style>标签和样式字符串
        var style = document.createElement('style');
        var cssTextNode = document.createTextNode(selector + '{' + css + '}');
        style.type = 'text/css';
        style.id = style_id;
        style.appendChild(cssTextNode); // 将样式字符串append到<style>标签里
        document.getElementsByTagName('head')[0].appendChild(style); // 将拼接好的<style>标签append到<head>
    }
    // 监听窗口的尺寸的重新计算(改变)
    window.onresize = function (ev) {
        var deviceWidth = document.getElementsByTagName('body')[0].offsetWidth;
        var height = 'height:' + (deviceWidth/3 - 2) + 'px';
        adaptive_img_height('.img-box img', height, 'imgAdaptive')
    };

    adaptive_img_height('.img-box img', height, 'imgAdaptive');
</script>
</html>

猜你喜欢

转载自blog.csdn.net/qq_39643614/article/details/82940781