【发布时间】:2017-07-27 13:05:37
【问题描述】:
我正在使用字体 consolas,我希望它在所有字符(等宽)中具有 15 像素高度和 7 像素宽度,并且具有 100% 精度(字符不必在视觉上拉伸,但它的框限制必须没有小数)。我一直在搞乱 CSS font-size 属性,但数字是如此随机。这是一个例子:
function Update(){
document.getElementById('Size').style.fontSize = document.getElementById('Input').value + "px";
document.getElementById('Width').innerHTML = document.getElementById('Size').getBoundingClientRect().width;
document.getElementById('Height').innerHTML = document.getElementById('Size').getBoundingClientRect().height;
}
Update()
span {
font-family: consolas;
}
<span id="Size">1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890</span>
<br>
<br>
<span>Font size: </span><input id="Input" oninput="Update()" value="12.7399992942810049711965802998747676610946655273437">
<br>
<span>Width (100 characters): </span><span id="Width"></span>
<br>
<span>Height (1 character): </span><span id="Height"></span>
您可以更改该输入的大小并检查它是否低于 700(7 像素 + 100 个字符)。太随意了,看不懂另外,我刚刚注意到这是限制,如果最后添加 5,则宽度为 700.4375,但如果添加 4,则可以添加世界上所有无关紧要的 9(可能是浮动限制东西)。
尚未进行更精确的测试(超过 100 个字符),但我想要的是拥有 15x7 大小的简单等宽字体,这样我就不必再担心奇怪的大小问题了。
用解决方案编辑(接受答案后):
<span> 的工作值,宽度和/或高度最多为 3000 个字符。
for(var i=0;i<3000;i++){ // 3000
document.getElementById('Size').innerHTML += "1"; // "1<br>" for some reason here in the Code Snippet the height is 53997 instead of 45000
}
function Update(){
document.getElementById('Size').style.fontSize = document.getElementById('Input').value + "px";
document.getElementById('Width').innerHTML = document.getElementById('Size').getBoundingClientRect().width;
document.getElementById('Height').innerHTML = document.getElementById('Size').getBoundingClientRect().height;
}
Update()
span {
font-family: consolas;
letter-spacing: 0.001192px; // 0.001192 to 0.001196
}
<span id="Size"></span><br>
<input id="Input" oninput="Update()" value="12.739"> <span id="Width"></span><span>x</span><span id="Height"></span>
【问题讨论】:
-
我猜你的身高需要
line-height: 1.. -
line-height: 1 根本不起作用,您需要为 line-height 提供一个单位。 100% 或绝对值。
标签: javascript html css fonts font-size