首页 > 解决方案 > 扩展到父级时如何使字体大小变小

问题描述

在 CSS 中,例如这段代码:

<html>
<head>
  <style>
* {
  box-sizing:border-box;
}
.container {
height:100px;
width:400px;
}
  </style>
</head>
<body>
  <button id="click" />
  <div class="container">
    <p id="text" ></p>
  </div>
</body>
  <script>
  Some function() {
    //code that adds 'text' to the paragraph every click
  }

  Some another function() {
    Some if(text extends to the width of the parent, then lower the font-size) {
    }
  }
  </script>
</html>

如果宽度扩大,如何使字体大小越来越小?就像每次点击按钮都会在段落上添加“文本”,所以当我重复多次时,就像:texttexttexttexttext等等,如果它扩展则降低字体大小

标签: javascripthtmlcssfont-size

解决方案


这是一种方法。运行下面的脚本,注释在里面以帮助理解。

注意:您没有提供如何增加宽度。在您的代码中,容器上设置了 400px 的宽度。除非您通过媒体查询或 JavaScript 进行更改,否则此宽度不会更改。

//Get text element by id "text"
  var text = document.getElementById("text");
  //Get div element by id "container"
  var container = document.getElementById("container");
  //Get current container width
  var w = container.offsetWidth;
  console.log(w);
  
   function addText() {
   //if nothing exists within p element add "text" or if something does exist increment "text"
    if (text.innerHTML.length <= 1  || text.innerHTML.length >= 1) {
    text.innerHTML += "text";
    }
    //check the container width and increase font size based on width
    if (w > 300) {
    text.style.fontSize = "50px"
    }
  }
<html>
<head>
  <style>
* {
  box-sizing:border-box;
}
.container {
height:100px;
width:400px;
}
.paragraph {
font-size: 12px;
}
  </style>
</head>
<body>
  <button onclick="addText();" id="click" />Click Me</button>
  <div class="container" id="container">
    <p class="paragraph" id="text"></p>
  </div>
</body>
</html>


推荐阅读