我使用的框架需要一个模态窗口的显式像素,用于在系统的各个点向最终用户显示消息。消息将始终是纯文本,因此我希望将宽度基于消息中的字符数。消息可以是2个单词或2个段落。
起初我尝试了直接乘法,这对于150-300的content.length
很有效,但是任何< 150都太小而且> 300太大了。
我需要一个算法的帮助,这个算法会产生比影响大量数字更小的数字。我希望它具有以下粗略的效果:
getWidthForContent("small message") = 120; //13 chars
getWidthForContent("another reasonable length for a modal message") = 300; //45 chars
getWidthForContent("lorem ipsum...") = 900; //600+ chars
您可以看到另一种方法是尝试从曲线中找到乘数值。这是一个非常草率的方法:
determineBestWidth: function (contentLength) {
var width = 900; //max
if (contentLength < 200) {
width = contentLength * 2;
if (contentLength < 125) {
width = contentLength * 3;
if (contentLength < 50) {
width = contentLength * 5;
if (contentLength < 20) {
width = contentLength * 10;
if (contentLength < 10) {
width = contentLength * 20;
}
}
}
}
}
return width;
},
原谅我缺乏数学技能
答案 0 :(得分:1)
您需要使用相同的模态内容创建隐藏的div 然后使用一些CSS技巧,你将能够做你想做的事情(如果我明白你想要什么):
var modal = document.getElementById("modal");
var modalHidden = document.getElementById("modalHidden");
modalHidden.innerHTML = modal.innerHTML;
var height = (modalHidden.clientHeight + 1) + "px";
var width = (modalHidden.clientWidth + 1) + "px";
var result = document.getElementById("result");
result.innerHTML = "Height : " + height + "<br/>Width : " + width;
if (parseInt(width.substring(0, width.length - 2)) < 500)
{
modal.style.width = width;
}
#modal {
border: 1px solid darkblue;
border-radius: 4px;
text-align: justify;
background-color: #a4b8ff;
padding: 10px;
width: 500px;
word-wrap :break-word;
margin-bottom: 40px;
}
#modalHidden
{
visibility: hidden;
white-space: nowrap;
width: auto;
height: auto;
position: absolute;
}
#info {
color: grey;
margin-bottom: 40px;
}
<div id="info">Add some text and see that the width changes. Just use the variable in the JS and you're good.</div>
<div id="modal">
Some short text
</div>
<div id="modalHidden"></div>
<div id="result"></div>
<小时/> 我做了jsFiddle,如果你想“玩”它。
积分转到Bacon Ipsum。