【问题标题】:Fit to text within the div适合 div 内的文本
【发布时间】:2017-11-19 07:26:11
【问题描述】:

我需要在固定宽度的容器中放置合适的文本,例如我有 150px 的宽度,特别是 div,但文本是动态的,因此基于一个字体大小的变化并适合容器,请建议

注意: 只有 javascript

【问题讨论】:

  • 如果您不想要基于 CSS 的解决方案,为什么要添加 css 标签? :)
  • 创建jsfiddle.net 向我们展示您的尝试。
  • p/span/h 标签上添加 width: inherit 到 css - 应该工作:) (可以用纯 js/jQuery 完成 - 我知道在 jQuery 中是 $('#elem').css('prop', 'value') - 不知道那是什么纯js
  • @ThisGuyHasTwoThumbs 我认为 OP 想要更改字体大小,以便文本适合 150px div,无论它有多长
  • @Pete 啊我明白了!然后需要overflow: scroll 或类似的东西

标签: javascript html


【解决方案1】:

你可以用这个方法,从这个答案中偷来的:

How to: Reduce font-size if a line breaks

由 AlexK 撰写

var divWidth = $("#theDiv").width();
var text = $("#text");
var fontSize = 12;

while (text.width() > divWidth)
  text.css("font-size", fontSize -= 0.5);

text.css("display", "inline");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="theDiv" style="width:200px; border:1px solid red;">
  <span id="text" style="display:none;white-space:nowrap;">This sentence is too large to fit within the div.</span>
</div>

请注意,您需要 JQuery。

如果你不想用jQuery,用JS代替应该不难。

JSFiddle

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-15
    • 2012-09-10
    • 2015-09-16
    • 1970-01-01
    • 1970-01-01
    • 2017-02-17
    • 2017-03-29
    相关资源
    最近更新 更多