Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
158 views
in Technique[技术] by (71.8m points)

javascript - How to: Reduce font-size if a line breaks

I have a span inside of a div and the div must remain 200px wide and the text must fit on one line within the div. The text within the span is dynamically generated so I can't possibly know which content will break to a new line and which will not.

<div style="width:200px">
  <span style="font-size:12px;">This sentence is too large to fit within the div.</span>
</div>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

One fairly nasty way: loop decreasing the overflowing span until its less that the div width;

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...