提问者:小点点

动态调整div的css缩放以适应容器的大小


假设这样的html代码:

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

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

  • “123”
  • '

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

我想对应用css“缩放”样式,以确保它的大小小于编辑器

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


共1个答案

匿名用户

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

这实际上是:

  • 对元素进行样式设置,使其自然溢出
  • 一次降低5%
  • 子元素小于其父元素时停止

null

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>