2016-06-23 204 views
1

我正在使用一个框架,要求显式像素用于模态窗口,该窗口将用于在系统中的各个点向最终用户显示消息。消息将始终为纯文本,所以我想根据消息中的字符数来确定宽度。消息可以是2个字或2个段落。根据内容长度设置显式模态宽度

起初我尝试了直接乘法,这对于150-300的content.length非常适用,但是任何东西太小而大于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

所以,你想计算在px的消息宽度,是吗? – tektiv

+0

关闭,我想根据消息中的字符数来计算px中合适的模式长度 – stackoverfloweth

+0

您是否在此模式中使用了“自动换行”?例如最大500像素,然后它打破了另一条线,其余的写。 – tektiv

回答

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) 
 
{ 
 
\t 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>


我做了一个,如果你婉与之“玩”。

积分去Bacon Ipsum

+0

尝试运行的内容“东西很小”,它看起来像模态宽度仍然是500+ https://jsfiddle.net/k4cdpw0c/ – stackoverfloweth

+0

@godmode是的,我的坏,忘了这部分。我更新了[小提琴](https://jsfiddle.net/bnokcaLu/)和片段。它现在应该工作。 – tektiv

+0

我很欣赏你的意见,但这不是我所期望的。你基本上介绍了最大宽度的概念。我想要一个算法的原因是像'这是一个非常整齐的发音。希望下一个会落在下面。“这不是一个过长的信息,所以在300px的时候,一直到500px都没有意义,它会破坏一次,看起来好多了。那有意义吗?我仍然会上传你的答案,我很抱歉。 – stackoverfloweth

相关问题