javascript - 扩展到父级时如何使字体大小变小
问题描述
在 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等等,如果它扩展则降低字体大小
解决方案
这是一种方法。运行下面的脚本,注释在里面以帮助理解。
注意:您没有提供如何增加宽度。在您的代码中,容器上设置了 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>
推荐阅读
- node.js - 如何docker化复合节点js项目
- r - 有谁知道如何让我的代码运行得更快?
- git - 通过 SSH 连接 github 返回权限被拒绝错误
- ios - 在 UserDefaults 的数组中更改字典中的值
- ibm-cloud - 如何更新 ibmcloud 中包含多个操作的包?
- google-apps-script - 如何使用 Apps 脚本在 BigQuery 中运行查询并将结果保存在表中?
- php - 尝试在 laravel 中的表或其关系中搜索
- asp.net-core - .Net Core 5.0 - 在注册时向用户添加角色
- lua - Lua/love2d - 游戏的资产文件夹路径
- cookies - 管理从其他服务器 next.js 接收到的服务器中的 cookie