javascript - 动态调整 div 的 css 缩放以适应容器的大小
问题描述
假设这样的html代码:
<editor>
<tree></tree>
</editor>
在我的应用程序中,tree
用于存储用户的输入,例如:
- '123'
- '111111111111111111111111111111111111111111111111111111'
因此,如果文本太长,可能会溢出。
我想将 css 'zoom' 样式应用于tree
,以确保它的大小小于editor
.
如何使用 JavaScript 计算完美缩放?
解决方案
您可以有效地逐步缩小它,直到它适合容器。
实际上这是:
- 对元素进行样式设置,使其自然溢出
- 一次降低 5%
- 一旦子元素小于它的父元素就停止
function calcSize() {
// The elements we need to use and our current scale
var editor = document.getElementById("editor")
var tree = document.getElementById("tree")
var scale = 1;
// Reset the initial scale and style incase we are resizing the page
tree.classList.add("loading");
tree.style.transform = "scale(1)";
// Loop until the scale is small enough to fit it's container
while (
(editor.getBoundingClientRect().width <
tree.getBoundingClientRect().width) &&
(scale > 0) // This is just incase even at 0.05 scale it doesn't fit, at which point this would cause an infinate loop if we didn't have this check
) {
// Reduce the scale
scale -= 0.05;
// Apply the new scale
tree.style.transform = "scale(" + scale + ")";
}
// Display the final result
tree.classList.remove("loading");
console.log("Final scale: " + Math.round(scale * 100) / 100)
}
// Run on load and on resize
calcSize();
window.addEventListener("resize", calcSize);
#editor {
display: block;
max-width: 50%;
font-size: 20px;
border: 1px solid #000;
overflow: visible;
}
#tree {
display: inline-block;
white-space: nowrap;
/* This is important as the default scale will be relative to the overflowed size */
transform-origin: 0 50%;
}
#tree.loading {
opacity: 0;
}
<editor id="editor">
<tree id="tree" class="loading">This is some overflowing text This is some overflowing text.</tree>
</editor>
(尝试全屏查看片段并调整窗口大小以查看它的效果)
推荐阅读
- php - 如何在 cmd 提示符下获取 php-cli 版本 7
- openxml - 演示 OpenXml 包无法找到字体颜色的来源
- json - 如何使用 entityframework ICollection '我的方式'进行序列化
- css - 将 node_module 插件 css 导入下一个 js 项目
- php - 刀片视图中的 Laravel 查询
- javascript - Angular 渐进式 Web 应用程序在 localhost 上工作,但不在 IP 上
- azure - 未找到资源组下的资源 (SQL Server)
- deployment - 以编程方式将 Power BI 报表部署到 Power BI 报表服务器并更改连接字符串
- odoo - 将数据从父类的一对多字段发送到向导通过单击父类中的按钮打开
- dialogflow-es - 如何访问 Google 助理命令(IFTTT 与 DialogFlow)?