2016-06-23 119 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

相關問題