You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用JavaScript判断图片宽度是否超过80%并调整尺寸

如何用JavaScript判断图片宽度是否超过80%并调整尺寸

看起来你想要实现的是让图片在保持原始比例的同时,最大尺寸不超过视口的80%宽或80%高对吧?我来帮你把这个逻辑用JavaScript写出来,直接套进你的代码里就行:

首先理清楚核心逻辑:

  • 必须等图片完全加载后再计算尺寸,不然拿不到准确的原始宽高比
  • 先算出视口80%的宽度和高度阈值
  • 根据图片原始比例,判断按80%高度显示时的宽度是否超标
  • 超标就切换为按80%宽度显示,同时按比例缩放高度;没超标就正常按80%高度显示

调整后的HTML代码

<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8">
<title>Aerocello</title>
<meta name="viewport" content="width=device-width,initial-scale=1">
<link rel="stylesheet" href="stylesheet.css">
<body>
    <div class="gallery">
        <!-- 给图片加个id方便JS获取,也可以继续用类名,id更直接 -->
        <img src="logo2.png" alt="logo" class="centre" id="mainLogo">
    </div>
    <div class="idk">
        <p class="roboto">hi</p>
    </div>

    <!-- 把script放在body末尾,确保DOM元素已被解析 -->
    <script>
        // 获取目标图片元素
        const logoImg = document.getElementById('mainLogo');

        // 定义尺寸调整的核心函数
        function adjustImageSize() {
            const viewportWidth = window.innerWidth;
            const viewportHeight = window.innerHeight;

            // 计算视口80%的阈值
            const maxAllowedWidth = viewportWidth * 0.8;
            const maxAllowedHeight = viewportHeight * 0.8;

            // 图片的原始宽高比(加载完成后才能拿到真实值)
            const imageRatio = logoImg.width / logoImg.height;

            // 先假设按最大高度显示,计算对应的宽度
            const widthIfUseMaxHeight = maxAllowedHeight * imageRatio;

            if (widthIfUseMaxHeight > maxAllowedWidth) {
                // 若按最大高度算的宽度超标,就按最大宽度来,高度自动适配
                logoImg.style.width = `${maxAllowedWidth}px`;
                logoImg.style.height = 'auto';
            } else {
                // 没超标就按最大高度显示,宽度自动适配
                logoImg.style.height = `${maxAllowedHeight}px`;
                logoImg.style.width = 'auto';
            }
        }

        // 监听图片加载完成事件
        logoImg.onload = adjustImageSize;

        // 处理图片已缓存的情况(此时onload可能不触发)
        if (logoImg.complete) {
            adjustImageSize();
        }

        // 可选:监听窗口大小变化,实时调整图片尺寸
        window.addEventListener('resize', adjustImageSize);
    </script>
</body>
</html>

对应的CSS优化(去掉冗余的绝对定位,用flex更简洁地居中)

body {
    background-color: #AEAEAE;
    margin: 0;
    padding: 0;
    height: 100vh;
}

.gallery {
    display: flex;
    /* 用flex的居中属性替代绝对定位,更适配动态尺寸 */
    justify-content: center;
    align-items: center;
    height: 100%;
}

.centre {
    /* 去掉原来的绝对定位、transform等,让JS控制核心尺寸 */
    width: auto;
    height: auto;
    max-width: 100%;
    max-height: 100%;
}

.roboto {
    font-family: roboto;
}

额外说明下:你的代码里出现了*ngFor,看起来像是Angular项目?如果是在Angular环境中,其实可以用@ViewChild获取图片元素,在ngAfterViewInit钩子中处理逻辑,不过上面的原生JS代码在Angular里也能正常运行~

备注:内容来源于stack exchange,提问作者Cosmac

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.14 17:08:14