我正在使用字体控制台,我希望它有15个像素的高度和7个像素的宽度在所有字符(单空间)以100%的精度(字符不必在视觉上拉伸,但它的框限制必须没有小数)。我一直在使用CSSfont-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(7px+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>

最佳答案

能够使用CSSletter-spacing: 0.001px;属性执行此操作:

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.001px;
}

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

希望这就是你要找的

关于javascript - 高度为15px,宽度为7px的等宽字体,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42646339/

10-09 14:37