gpt4 book ai didi

javascript - 是否可以根据容器制作动态字体大小?

转载 作者:太空宇宙 更新时间:2023-11-03 21:08:59 25 4
gpt4 key购买 nike

我有一个具有特定尺寸的元素(我的意思是恒定的宽度和高度)。我想更改其中文本的字体大小,以避免从容器中溢出一些东西。

div {
border: 1px solid;
height: 60px;
width: 200px;
margin: 30px;
}
<div>
whatever this is. this is a test. whatever this is. this is a test.
</div>


<div>
whatever this is. this is a test. whatever this is. this is a test. whatever this is. this is a test. whatever this is. this is a test.
</div>

在这个 ^ fiddle 中,第一个 <div> 的字体大小应该更大以填充容器,在第二个中,字体大小应该更小,因为容器中不应有任何东西流出。

知道我该怎么做吗?

最佳答案

设置一个默认的font-size,如果内容溢出这个字体大小那么下面的代码片段将减小字体大小

// checking if with current font size if the text is overflowing
function isOverflown(element) {
return element.scrollHeight > element.clientHeight || element.scrollWidth > element.clientWidth;
}

// get all div and itrate over the array
document.querySelectorAll('div').forEach(function(item) {
// get the font size and
let fontSize = parseInt(window.getComputedStyle(item, null).getPropertyValue("font-size"), 10);
// for the font size check if the current content is overflowing the container
for (let i = fontSize; i >= 0; i--) {
let overflow = isOverflown(item);
// if overflowing then reduce the font size
if (overflow) {
fontSize--;
// add the font size property to the container
item.style.fontSize = fontSize + "px";
}
}
})
div {
border: 1px solid;
height: 60px;
width: 200px;
margin: 30px;
font-size: 20px;
}
<div>
whatever this is. this is a test. whatever this is. this is a test.
</div>


<div>
whatever this is. this is a test. whatever this is. this is a test. whatever this is. this is a test. whatever this is. this is a test.whatever this is. this is a test. whatever this is. this is a test. whatever this is. this is a test. whatever this
is. this is a test.whatever this is. this is a test. whatever this is. this is a test. whatever this is. this is a test. whatever this is. this is a test.whatever this is. this is a test. whatever this is. this is a test. whatever this is. this is a
test. whatever this is. this is a test.
</div>

关于javascript - 是否可以根据容器制作动态字体大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48970675/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com