2012-09-10 52 views
1

我想添加一個簡單的工具提示到我的菜單。如何計算我的 工具提示中的文字有多少像素?使用jQuery計算文字像素寬度

HTML:

<nav> 
    <ul> 
     <li> 
      <a href="#" title="Item 1 text">Item 1</a> 
     </li> 
     <li> 
      <a href="#" title="Item 2 longer text" >Item 2</a> 
     </li> 
     <li> 
      <a href="#" title="Item 3 text text text">Item 3</a> 
     </li> 
    </ul> 
</nav> 

CSS:

nav{ 
    position: fixed; 
    left:0; 
    right:0; 
    bottom:0; 
    height:30px; 
    background: grey; 
} 
ul{ 
    width: 300px; 
    margin:0 auto; 
} 
li{ 
    float:left; 
    position:relative; 
} 
span{ 
    position:absolute; 
    left: 50%; 
    bottom: 30px; 
    background:black; 
    border: solid 1px grey; 
    border-bottom:none; 
    display:none; 
    color:white; 
} 
li:hover span{ 
    display:block; 
} 
a{ 
    display:block; 
    text-decoration:none; 
    color: white; 
    line-height: 30px; 
    padding: 0 10px; 

}​ 

的jQuery:

$(document).ready(function(){ 
    $('nav li').each(function(){ 
     $(this).append('<span>'+$(this).find('a').attr('title')+'</span>'); 
    }); 
    $('nav li span').each(function(){ 
     // var textwidth = ???? 
     // $('nav li span').css("left",-textwidth/2); 
     // $('nav li span').css("width",textwidth); 
    }); 
}); 

演示:
http://jsfiddle.net/vxUTZ/1/

+0

'$(本)的.text()length'找到。通過使用大腦 –

+0

你正在計算有多少個字符,而不是這些字符的寬度 – Puyol

+0

GJ sherlock,所以你只需要問一下css屬性的textwidth,因爲它在每個設備上的每個瀏覽器中都不同...... –

回答

3
$(this).width(); 

使用和你會得到你的跨度的寬度,但在你必須改變你的CSS中的空白行爲-part:

span { white-space: nowrap; } 

有了這個,不會有斷行後,每空格和計算的寬度是文本的寬度

+0

這就是我需要的,謝謝! – Puyol

0

使用

$(this).width(); 

,或者您也可以使用

$(this).attr("width"); 

在你的功能。如果要CAL上面的代碼文本lenght然後

$(this).text().length; 
+0

我需要的文本的寬度,如果他們其中一個上線,而非字符數跨度 – Puyol

+0

然後把$(本)。 。文本()寬度();或$(this).attr(「width」) – Gautam3164

+0

無法正常工作 – Puyol