首页 > 解决方案 > 动态调整 div 的 css 缩放以适应容器的大小

问题描述

假设这样的html代码:

<editor>
    <tree></tree>
</editor>

在我的应用程序中,tree用于存储用户的输入,例如:

因此,如果文本太长,可能会溢出。

我想将 css 'zoom' 样式应用于tree,以确保它的大小小于editor.

如何使用 JavaScript 计算完美缩放?

标签: javascripthtmlcss

解决方案


您可以有效地逐步缩小它,直到它适合容器。

实际上这是:

  • 对元素进行样式设置,使其自然溢出
  • 一次降低 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>

(尝试全屏查看片段并调整窗口大小以查看它的效果)


推荐阅读