2013-08-26 54 views
1

我需要一種方法來預測一個字符串的寬度,如果它是一個元素內添加。聰明的方式來預測寬度

的字體大小是16像素。 我最初的想法是爲每個角色做16px,但最終出錯了。任何想法?

+0

仍撲朔迷離的寬度,更多的信息,你的問題補充。 – Praveen

+0

[這](http://www.foliotek.com/devblog/getting-the-width-of-a-hidden-element-with-jquery-using-width/)可能的幫助。 (由[先前的問題]啓發(http://stackoverflow.com/questions/1472303/jquery-get-width-of-element-when-not-visible-display-none)。) – Taymon

+0

它給你添加隱藏的元素附加所有文本並獲取其寬度 –

回答

1

您可以將字符串追加到身體像這樣:

function get_width_of_string() { 
    var div = document.createElement('div'); 
     div.style.position = "absolute"; 
     div.style.marginLeft = "-99999px"; 
     div.style.display = "inline-block"; 
    div.innerHTML = "this is a string"; 

    document.body.appendChild(div); 

    var width = div.offsetWidth; 
    document.body.removeChild(div); 
    return width; 
} 

這應該返回字符串

相關問題