如何使用Javascript根据div内容的大小缩放div内容



我有一个div,它位于页面的中心,并以保持其纵横比(16:9)的方式随视口缩放。问题是,我希望里面的字体和内容也能随着div的大小而缩放。Vmin在大多数情况下都能正常工作。如果div的纵横比为1:1,它将完美工作,因为vmin直接检查视口的高度和宽度之间的较小值,并且您不能设置自定义纵横比。

<!DOCTYPE html>
<html>
<head>
<style>
body {
background-color:white;
}
.wrapper {
width: 95vw;
height: calc(95vw * 9/16);
max-height: 95vh;
max-width: calc(95vh * 16/9);
background: center;
background-color: blue;
background-size:contain;
margin: auto;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
#lorem {
color: aqua;
font-size:10vmin;
text-align:center;
position:absolute;
transform: translate(-50%, -50%);
top: 50%;
left: 50%;
margin:auto;
}
</style>
</head>
<body>
<div class="wrapper">
<p id="lorem">
This text should scale with div only.
</p>
</div>
</body>
</html>

https://jsfiddle.net/Addictorator/70fq44sv/2/

垂直调整窗口大小以查看我在说什么。

我不相信在纯css中有任何方法(但如果有,那将是最可取的),但我认为在javascript中使用事件监听器onresize来调整div的大小,并通过比较原始(或以前存储为var)div高度/宽度与当前div高度/宽度的比率来分别缩小每个元素是可能的。或者,它可以尝试复制vmin行为,但将高度设置为16:9而不是1:1的比例,就像上面使用css在div上所做的那样。如果可能的话,我更喜欢纯js,而不是jquery。我自己也试过这样做,但在javascript方面我相当业余。

提前感谢!

请查看此处的工作代码笔。

解决方案非常简单。在窗口调整时,我们返回父窗口的clientHeight。通过除以返回的值,我们得到了一个可用作CCD_ 1的整数。然后,我们将其分配给p元素。

我希望这能解决你的问题。

//assigns font-size when document is ready
document.onreadystatechange = () => {
if (document.readyState === 'complete') {
var wrapperHeight = document.getElementById('wrapper').clientHeight;
var relativeFontSize = wrapperHeight / 10 + 'px'; //change 10 to any  integer for desired font size
document.getElementById("lorem").style.fontSize = relativeFontSize;
}
};
//then on window resize
window.onresize = function(event) {
var wrapperHeight = document.getElementById('wrapper').clientHeight;
var relativeFontSize = wrapperHeight / 10 + 'px'; //change 10 to any integer for desired font size
document.getElementById("lorem").style.fontSize = relativeFontSize;
};
body {
background-color:white;
}
#wrapper {
width: 95vw;
height: calc(95vw * 9/16);
max-height: 95vh;
max-width: calc(95vh * 16/9);
background: center;
background-color: blue;
background-size:contain;
margin: auto;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
font-size:60px;
}
#lorem {
color: aqua;
text-align:center;
position:absolute;
transform: translate(-50%, -50%);
top: 50%;
left: 50%;
margin:auto;

}
<div id="wrapper">
<p id="lorem">
This text should scale with div only.
</p>
</div>

最新更新