Aar*_*ken 4 html javascript formatting text
我有一个用户变量字符串,其范围可以从一个单词到几个句子(并且可能包含任何有效的 Unicode 字符),我希望将其显示在可变宽度框中。
在代码中,我希望 HTML 看起来像这样,带有任何其他 CSS 或 JS:
<div style="width: 100%; height: 80%" id="text">
<!--<some more divs or something>-->
{{content}}
<!--</some more divs or something>-->
</div>
Run Code Online (Sandbox Code Playgroud)
{{content}}
应该尽可能变大,达到某个最大字体大小(可变);当它更长到某个最小值(变量)时较小,然后在该点之后被切断。
无论哪种情况,我都需要它在视觉上居中,并且比框长的单词应该用连字符连接。
我尝试过结合 Flexbox 和 JavaScript 来破解一些东西,但不知道如何解决所有错误。
除了最新版本的移动/桌面 Chrome/Safari/Firefox 之外,浏览器支持并不重要。
正好。
看看这个小提琴。
我想我成功地做到了你想做的事。它适用于 Chrome、Firefox 和 Safari。
HTML:
<div id="container">
<div id="text">my Text !!</div>
</div>
Run Code Online (Sandbox Code Playgroud)
JS:
var maxFontSize=68; // I think we cannot have bigger than that.
var minFontSize=12;
$('#text').on({
// setting an event to resize text
resize:function(e){
// if no text => return false;
if (!$(this).html().trim()) return;
// if already running => return false;
if (this.running) return;
this.running = true;
// get max-height = height of the parent element
var h = $(this).parent().height();
// clone the text element and apply some css
var clone = $(this).clone()
.removeAttr('id')
.css({'font-size':0,
'width':$(this).width(),
'opacity':0,
'position':'fixed',
'left':-1000})
.appendTo($('body'));
// Set the max font size for the clone to fit the max height;
var fontSize = minFontSize;
do {
$(this).css('font-size', fontSize+'px');
fontSize=fontSize+1;
clone.css('font-size', fontSize+'px');
} while (h > clone.height() && maxFontSize > fontSize) ;
// Set the '...' if still bigger
//start by setting back the good size to the clone.
fontSize=fontSize-1;
clone.css('font-size', fontSize+'px');
// while max-height still bigger than clone height
if (h < clone.height() && minFontSize == fontSize) {
var content = clone.html();
// try to remove the last words, one by one.
while (h < clone.height()) {
content = content.replace(/(\s[^\s]*)$/g,'...');
clone.html(content);
}
// then replace the #text content
$(this).html(clone.html());
}
// then remove the clone
clone.remove();
this.running = false;
}
})
.trigger('resize');
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
541 次 |
最近记录: |