使用js控制文字大小自动适应div不换行,div中文字字号自动调整大小以适应固定宽度

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
        <style>
            * {
                padding: 0;
                margin: 0;
            }
            #text-container {
                margin: 30px;
                width: 300px;
                height: 30px;
                border: 1px solid #000;
                overflow: hidden; /* 隐藏溢出的内容 */
            }

            #text-container p {
                font-size: 28px; /* 初始字体大小 */
                white-space: nowrap; /* 禁止文字换行 */
            }
        </style>
    </head>
    <body>
        <div id="text-container">
<p>fadffadffadffadffadffadffadffadffadffadffadffadffadffadffadffadffadffadffadffadffadffadffad	ffa中过</p>
        </div>
    </body>
    <script>
        window.addEventListener("DOMContentLoaded", adjustFontSize);

        function adjustFontSize() {
            const textContainer = document.getElementById("text-container");
            const textElement = textContainer.querySelector("p");

            let fontSize = parseInt(window.getComputedStyle(textElement).fontSize);

            while (textElement.scrollWidth > textContainer.clientWidth && fontSize > 10) {
                fontSize--;
                textElement.style.fontSize = `${fontSize}px`;
            }
            while (textElement.scrollWidth < textContainer.clientWidth - 10 && fontSize < 32) {
                 fontSize += 1
                 numberItem.style.fontSize = `${fontSize}px`
                 console.log(fontSize, '----fontSize')
             }
        }
    </script>
</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值