2013-01-16 85 views
0

我有一個函數切串到一個準確的寬度,我們稱這種cut()如何獲得空白的寬度?

cut('abcd',3) = 'abc'

中font-family我用的是Arial

但是當我計算出每個系統字符的寬度,我發現whitespace很奇怪。

<span id='x'> </span> 

當我使用$("#x").width()我得到了0.0

注意whitespace&nbsp

爲什麼' ' = 0.0'a b' that ' ' != 0.0

什麼的whitespaceHTML規則?

+2

Your titl e與您的問題不匹配......「寬度空白」感覺像字符串中呈現字符的寬度,但您在帖子中的問題似乎是「如何僅呈現沒有/僅空白內容的元素」。 –

回答

0

試試這個,因爲這裏特色:Calculating text width

$.fn.textWidth = function(){ 
     var html_org = $(this).html(); 
     var html_calc = '<span>' + html_org + '</span>'; 
     $(this).html(html_calc); 
     var width = $(this).find('span:first').width(); 
     $(this).html(html_org); 
     return width; 
    }; 

//切換功能