2011-07-02 79 views
0

我的代碼如下所示。首先警告顯示「test li 0」,其寬度爲1024.但1024寬度不正確。其實它大約是50像素。我想要文本的寬度「test li 0」。 我如何獲得文字寬度?我想用jquery查找「li」的總寬度。我怎樣才能獲得文字寬度?我該怎麼做?


$(document).ready(function() { 
var total = 0; 
var i=0; 

$('#menutop > span> li').each(function(index) { 

//var tesi = jQuery("#i_"+i).css('width'); 
var tesi = jQuery("#i_"+i).width(); 
alert(tesi + ':' + $(this).text()); 
total = parseInt(total) + parseInt(tesi); 
i=parseInt(i)+1; 

}); 
alert(total); 
}); 

<ul id="menutop"> 
    <span><li id="i_0" style="background-color:blue;"> test li 0 </li></span> 
    <span><li id="i_1" style="background-color:blue; width:150px;"> test li 1 </li></span> 
    <span><li id="i_2" style="background-color:blue; width:200px;"> test li 2 </li></span> 
</ul> 

+0

''在'li'之外是非法的。我會刪除那些第一個 –

+0

我已經刪除了跨度,但它會給我相同的寬度。 – vishal

+1

你是1000%確定它不是1024像素寬?因爲'li'元素通常是'display:block',佔用了整個屏幕的寬度。 –

回答

1

由於佩卡建議,你可以把跨度裏內,使用下面的算法:

$(document).ready(function() { 
var total = 0; 
var i=0; 

$('#menutop > li').each(function(index) { 

//var tesi = jQuery("#i_"+i).css('width'); 
var tesi = $(document.getElementById("i_"+i).firstChild).width(); 
alert(tesi + ':' + $(this).text()); 
total = parseInt(total) + parseInt(tesi); 
i=parseInt(i)+1; 

}); 
alert(total); 
}); 

<ul id="menutop"> 
    <li id="i_0" style="background-color:blue;"><span> test li 0 </span></li> 
    <li id="i_1" style="background-color:blue; width:150px;"><span> test li 1 </span></li> 
    <li id="i_2" style="background-color:blue; width:200px;"><span> test li 2 </span></li> 
</ul> 
+0

雖然沒有必要使用''#i _「+ i'。 '這個'會做 –

+0

它是警覺的第一和第二li寬度。二里寬後。它會給出錯誤。 : - 未捕獲的異常:[Exception ...「無法轉換JavaScript參數arg 0 [nsIDOMViewCSS.getComputedStyle]」nsresult:「0x80570009(NS_ERROR_XPC_BAD_CONVERT_JS)」位置:「JS frame :: http:// localhost/rnd/detect-screen -size/jquery.js :: anonymous :: line 12「data:no] – vishal

+0

在這裏嘗試了這個解決方案:jsfiddle.net/Kkwxj,它工作正常 –

1

達到你想要的結果,我想你應該將您的span s放入li s:

<ul id="menutop"> 
    <li id="i_0" style="background-color:blue;"><span> test li 0 </span></li> 
    <li id="i_1" style="background-color:blue; width:150px;"><span> test li 1 </span></li> 
    <li id="i_2" style="background-color:blue; width:200px;"><span> test li 2 </span></li> 
</ul> 

而做到這一點:

... 
$('#menutop > li > span').each(function(index) { //Note the order 
    var tesi = jQuery("#i_"+i+" span").width(); //Get span width instead of li's 
    //... the same code 

這是因爲李的會盡量佔據默認情況下所有的寬度(這就是爲什麼你有1024),但跨不這樣做,僅佔其內容的寬度。

希望這會有所幫助。歡呼聲

+0

雖然沒有必要使用''#i _「+ i'。 '這個'會做 –

0

只需更改一下你的代碼。

var tesi = jQuery("#i_"+i).width(); 

var tesi = jQuery("#i_"+i).css("display", "inline").width(); 
jQuery("#i_"+i).css("display", "block"); 

它暫時的電流轉換<li>內聯,計算出的寬度,然後將其轉換回框。

相關問題