将 div 收缩包装到某些文本非常简单。但是,如果文本由于最大宽度(例如)而换行到第二行(或更多行),则 DIV 的大小不会缩小到新换行的文本。它仍然扩展到断点(在本例中为最大宽度值),导致 DIV 右侧有相当多的边距。当想要将此 DIV 居中以使换行文本居中时,这是有问题的。不会,因为 DIV 不会收缩为换行的多行文本。一种解决方案是使用合理的文本,但这并不总是实用,而且单词之间的间隙很大,结果可能会很糟糕。
我知道没有解决方案可以将 DIV 缩小为纯 CSS 中的换行文本。所以我的问题是,如何用 Javascript 实现这一目标?
这个 jsfiddle 说明了这一点:jsfiddle。由于最大宽度,这两个单词几乎不会换行,但 DIV 不会收缩到新换行的文本,从而留下令人讨厌的右侧边距。我想消除这个问题,并使用 Javascript 将 DIV 的大小调整为包装文本(因为我不相信纯 CSS 中存在解决方案)。
.shrunken {text-align: left; display: inline-block; font-size: 24px; background-color: #ddd; max-width: 130px;}
<div class="shrunken">Shrink Shrink</div>
这不是最漂亮的解决方案,但它应该可以解决问题。逻辑是计算每个单词的长度,并用它来计算出在强制换行之前可以容纳的最长的行;然后将该宽度应用于 div。在这里小提琴:http://jsfiddle.net/uS6cf/50/
示例 HTML...
<div class="wrapper">
<div class="shrunken">testing testing</div>
</div>
<div class="wrapper">
<div class="shrunken fixed">testing testing</div>
</div>
<div class="wrapper">
<div class="shrunken">testing</div>
</div>
<div class="wrapper">
<div class="shrunken fixed">testing</div>
</div>
<div class="wrapper">
<div class="shrunken" >testing 123 testing </div>
</div>
<div class="wrapper">
<div class="shrunken fixed" >testing 123 testing </div>
</div>
和 javascript(依赖于 jQuery)
$.fn.fixWidth = function () {
$(this).each(function () {
var el = $(this);
// This function gets the length of some text
// by adding a span to the container then getting it's length.
var getLength = function (txt) {
var span = new $("<span />");
if (txt == ' ')
span.html(' ');
else
span.text(txt);
el.append(span);
var len = span.width();
span.remove();
return len;
};
var words = el.text().split(' ');
var lengthOfSpace = getLength(' ');
var lengthOfLine = 0;
var maxElementWidth = el.width();
var maxLineLengthSoFar = 0;
for (var i = 0; i < words.length; i++) {
// Duplicate spaces will create empty entries.
if (words[i] == '')
continue;
// Get the length of the current word
var curWord = getLength(words[i]);
// Determine if adding this word to the current line will make it break
if ((lengthOfLine + (i == 0 ? 0 : lengthOfSpace) + curWord) > maxElementWidth) {
// If it will, see if the line we've built is the longest so far
if (lengthOfLine > maxLineLengthSoFar) {
maxLineLengthSoFar = lengthOfLine;
lengthOfLine = 0;
}
}
else // No break yet, keep building the line
lengthOfLine += (i == 0 ? 0 : lengthOfSpace) + curWord;
}
// If there are no line breaks maxLineLengthSoFar will be 0 still.
// In this case we don't actually need to set the width as the container
// will already be as small as possible.
if (maxLineLengthSoFar != 0)
el.css({ width: maxLineLengthSoFar + "px" });
});
};
$(function () {
$(".fixed").fixWidth();
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)