动态调整div的CSS缩放以适合容器的大小

时间:2020-07-31 13:47:07

标签: javascript html css

假设这样的html代码:

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

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

  • '123'
  • '1111111111111111111111111111111111111111111111111111111111'

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

我想将css的“缩放”样式应用于tree,以确保其尺寸小于editor

如何使用JavaScript计算完美变焦?

1 个答案:

答案 0 :(得分:1)

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

有效的是:

  • 设置元素的样式,使其自然溢出
  • 一次缩小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>

(尝试以全屏方式查看代码段,并调整窗口大小以使其生效)

相关问题