【问题标题】:Make HTML input font size shrink as more type is typed输入更多类型时使 HTML 输入字体大小缩小
【发布时间】:2019-05-12 12:20:08
【问题描述】:
我有一个 3 个字符的 HTML 文本字段。如果用户输入 4 个字符,我希望缩小字体大小以适应这四个字符。
Acrobat 对表单有这种行为。我想要 HTML 中的这种行为。
也就是说,如果我有一个包含 3 个字符的文本字段:
而用户键入一个 4,我希望文字缩小:
【问题讨论】:
标签:
html
css
text
responsive-design
【解决方案2】:
我认为你想要的可以用一些非常简单的 javascript 方法来完成。但是,不幸的是,在 html 或 css 中没有这样做的方法。下一个代码是我发现的,由 u/adactio 编写。在 github 上。
<script>
window.fitText( document.getElementById("responsive_headline") );
</script>
window.fitText( document.getElementById("responsive_headline"), 1.2 );
// turn the compressor up (font will shrink a bit more aggressively)
window.fitText( document.getElementById("responsive_headline"), 0.8 );
// turn the compressor down (font will shrink less aggressively)
确保编辑掉“responsive_headline”!
干杯!
【解决方案3】:
您需要使用 javascript。
这通过检查输入是否可以滚动来工作,如果可以,则表示内容已溢出,在这种情况下,字体大小应该变小。
希望这会有所帮助!
function changefontsize() {
var myInput = document.getElementById('myInput');
if(isOverflown(myInput)) {
while (isOverflown(myInput)){
currentfontsize--;
myInput.style.fontSize = currentfontsize + 'px';
}
}else {
currentfontsize = 13;
myInput.style.fontSize = currentfontsize + 'px';
while (isOverflown(myInput)){
currentfontsize--;
myInput.style.fontSize = currentfontsize + 'px';
}
}
}
function isOverflown(element) {
return element.scrollWidth > element.clientWidth;
}
#myInput {
padding:5px;
border-radius:3px;
font-family:Arial;
width:100px;
font-size:13px;
height:20px;
}
Type Here -> <input type="text" id="myInput" onkeypress="changefontsize()" onchange="changefontsize()">