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

匿名用户

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

这实际上是:对元素进行样式设置,使其自然溢出

一次降低5%

子元素小于其父元素时停止

nullfunction 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;

}

This is some overflowing text This is some overflowing text.

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值