2012-04-28 53 views
0

我想用CSS和jQuery水平居中放置絕對位置的對象。 jQuery是必要的,因爲對象具有不同的寬度。將鼠標懸停在我的jsFiddle中的圖標上,查看我的意思。使用jQuery和CSS的中心對象

jsFiddle here

現在我應用了left: 50%屬性,但我需要做一個負margin-left是對象的寬度的一半。這是我的代碼,不知道爲什麼它不工作:

jQuery的

$('.tooltip').each(function() { 
     $(this).css('margin-left', '-'+($(this).width()/2)+'px'); 
}​ 

CSS

.toolbar .tooltip { 
    position: absolute; 
    left: 50%; 
    margin-top: 8px; 
    padding: 3px 8px; 
    display: none; 
} 

.toolbar li:hover .tooltip { 
    display: block; 
} 

HTML

<ul class="toolbar"> 
    <li><img alt="Undo" src="undo.gif" /><span class="tooltip">Undo</span></li> 
    <li><img alt="Redo" src="redo.gif" /><span class="tooltip">Redo</span></li> 
    <li><img alt="Help" src="help.gif" /><span class="tooltip">Help</span></li> 
    <li><img alt="Feedback" src="feedback.gif" /><span class="tooltip">Feedback</span</li> 
</ul> 
+0

有很多在你的提琴外部CSS的;如果可以的話,它可能有助於簡化它。 – machineghost 2012-04-28 20:56:29

+0

如果你仔細觀察,你的'每個'呼叫[沒有右括號](http://xkcd.com/859/)。代碼沒有運行,因爲它在語法上不正確。 – Cameron 2012-04-28 20:57:55

+0

@Cameron Gah!謝謝。 – colindunn 2012-04-28 21:00:07

回答

4

未關閉的代碼錯誤,更新的代碼here

順便說一句,它具有填充,所以你應該使用「outerWidth」而不是「寬度」。你可以基於塊的寬度校正碼here

+0

它不工作? – 2012-04-28 21:02:11

+0

我更新了代碼,提供了更通用的解決方案 – 2012-04-28 21:03:50

+0

@cubuzoa謝謝! – colindunn 2012-04-28 21:05:09

1

,我設置left因此。

$('.tooltip').each(function() { 
    // Assuming button block width is 32px. 
    $(this).css('left', (32 - ($(this).width()))/2+'px'); 
}​);​ 

http://jsfiddle.net/3Cb9A/3/

+0

聰明。如果按鈕的寬度一致,這將工作,但可能會改變。 – colindunn 2012-04-28 21:10:12