![]() |
谈吐大方的电池 · 第七届中美高校图书馆合作发展论坛 | CASHL· 3 月前 · |
![]() |
喝醉的哑铃 · 电子书自由!9个电子书下载网站,中英文社科书 ...· 1 年前 · |
![]() |
强健的碗 · 北京近半共享单车闲置 ...· 1 年前 · |
![]() |
喝醉的米饭 · 《星动甜妻夏小星》软萌小女仆,遇上大灰狼总裁· 1 年前 · |
![]() |
帅气的黄瓜 · 历史选择了邓小平(113)--邓小平纪念网- ...· 1 年前 · |
我需要显示用户输入的文本到一个固定大小的div。我想要的是自动调整字体大小,以便文本尽可能多地填满方框。
我可能想要从最大字体大小开始,当文本太大而无法容纳容器时,缩小字体大小,直到适合,并且字体必须显示为单行。只使用css和html就可以做到这一点吗?
发布于 2013-08-14 20:41:24
假设你有这个:
<div id="outer" style="width:200px; height:20px; border:1px solid red;">
<div>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer mollis dui felis, vel vehicula tortor cursus nec</div>
</div>
然后,您可以执行以下操作:
$(document).ready(function () {
resize_to_fit();
function resize_to_fit(){
var fontsize = $('div#outer div').css('font-size');
$('div#outer div').css('fontSize', parseFloat(fontsize) - 1);
if($('div#outer div').height() >= $('div#outer').height()){
resize_to_fit();
}
工作样本
$(document).ready(function() {
resize_to_fit();
function resize_to_fit() {
var fontsize = $('div#outer div').css('font-size');
$('div#outer div').css('fontSize', parseFloat(fontsize) - 1);
if ($('div#outer div').height() >= $('div#outer').height()) {
resize_to_fit();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="outer" style="width:200px; height:20px; border:1px solid red;">
<div>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer mollis dui felis, vel vehicula tortor cursus nec</div>
</div>
发布于 2020-11-13 22:52:21
基于这里顶层 answer 的逻辑,我创建了一个no-jQuery版本,
const input = document.querySelector('input');
const output = document.querySelector('.output');
const outputContainer = document.querySelector('.container');
function resize_to_fit() {
let fontSize = window.getComputedStyle(output).fontSize;
output.style.fontSize = (parseFloat(fontSize) - 1) + 'px';
if(output.clientHeight >= outputContainer.clientHeight){
resize_to_fit();
function processInput() {
output.innerHTML =this.value;
output.style.fontSize = '100px'; // Default font size
resize_to_fit();
input.addEventListener('input', processInput);
<input type="text" placeholder="Add text input here" style="margin: 10px; width:50%;">
<div id="outer" class="container"
style="width:80%; height:100px; border:2px solid red; font-size:20px;">
<div class="output" style="word-break: break-all; word-wrap: break-word;">
</div>
发布于 2013-08-14 20:40:56
获取文本字符串的像素大小是一件很难做的事情,并且在很大程度上取决于浏览器和用户的设置,因此可能很难想出一个在所有情况下都有效的解决方案。
“显示用户输入的文本”是指用户正在文本框中键入内容吗?如果是这样,您可以附加一个按键侦听器来检查文本值的长度,然后相应地调整
font-size
。下面是一个示例,不过您可能需要更改长度和字体大小以满足您的需要:
$('#text').on('keypress', function(e) {
var that = $(this),
textLength = that.val().length
if(textLength > 30) {
that.css('font-size', '5px');
![]() |
谈吐大方的电池 · 第七届中美高校图书馆合作发展论坛 | CASHL 3 月前 |
![]() |
喝醉的米饭 · 《星动甜妻夏小星》软萌小女仆,遇上大灰狼总裁 1 年前 |
![]() |
帅气的黄瓜 · 历史选择了邓小平(113)--邓小平纪念网--人民网 1 年前 |