|
|
奔跑的炒面 · 中華民國對外貿易發展協會-全球網絡· 5 月前 · |
|
|
傻傻的作业本 · 杭州教育论坛-杭州幼儿园_幼升小_小升初_中 ...· 6 月前 · |
|
|
善良的莴苣 · 火焰纹章圣剑系谱攻略_九游手机游戏· 10 月前 · |
|
|
俊逸的杯子 · 九连工委“大搞”反“三征”-河源市人民政府门户网站· 1 年前 · |
|
|
重感情的围巾 · 内存取证-volatility工具的使用 ...· 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');
|
|
奔跑的炒面 · 中華民國對外貿易發展協會-全球網絡 5 月前 |
|
|
善良的莴苣 · 火焰纹章圣剑系谱攻略_九游手机游戏 10 月前 |
|
|
俊逸的杯子 · 九连工委“大搞”反“三征”-河源市人民政府门户网站 1 年前 |