【问题标题】:How to make font-size smaller when it extends to a parent [duplicate]扩展到父级时如何使字体大小变小[重复]
【发布时间】:2021-02-05 14:47:24
【问题描述】:

在 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等等,如果它扩展则降低字体大小

【问题讨论】:

  • 查看您的历史记录后,我注意到您提出问题并且没有将答案标记为有用、正确或向试图帮助您的人提供任何反馈。 - 在本网站上,如果您进行交流、支持有用的答案或将答案标记为正确,它将帮助您并证明人们花在帮助您上的时间是合理的。无论如何,我希望我的回答对您的问题有所帮助。 - 祝你好运。

标签: javascript html css font-size


【解决方案1】:

这是一种方法。运行下面的脚本,里面有cmets来帮助理解。

注意:您没有提供如何增加宽度。在您的代码中,容器上设置了 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>

【讨论】:

    猜你喜欢
    • 2018-09-16
    • 1970-01-01
    • 2014-08-29
    • 2014-04-11
    • 1970-01-01
    • 1970-01-01
    • 2016-04-27
    • 2021-05-04
    • 1970-01-01
    相关资源
    最近更新 更多