使用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>Documenttitle>
        <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>

你可能感兴趣的:(javascript,前端,css)