Javascript 使用jQuery和CSS设置中心对象

Javascript 使用jQuery和CSS设置中心对象,javascript,jquery,html,css,Javascript,Jquery,Html,Css,我正试图用CSS和jQuery将绝对定位对象水平居中。jQuery是必需的,因为对象的宽度不同。将鼠标移到JSFIDLE中的图标上,查看我的意思 现在我应用了一个left:50%属性,但是我需要做一个负的marginleft,它是对象宽度的一半。这是我的代码,不知道为什么不起作用: jQuery $('.tooltip').each(function() { $(this).css('margin-left', '-'+($(this).width() / 2)+'px'); }​

我正试图用CSS和jQuery将绝对定位对象水平居中。jQuery是必需的,因为对象的宽度不同。将鼠标移到JSFIDLE中的图标上,查看我的意思

现在我应用了一个
left:50%
属性,但是我需要做一个负的
marginleft
,它是对象宽度的一半。这是我的代码,不知道为什么不起作用:

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>
  • 撤消
  • 重做
  • 帮助

  • 反馈未关闭代码错误,更新代码


    顺便说一下,它有填充,所以你应该使用“outerWidth”而不是“width”。你可以更正代码

    未关闭的代码错误,更新代码


    顺便说一下,它有填充,所以您应该使用“outerWidth”而不是“width”。您可以根据块的宽度更正代码,我相应地设置
    left

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

    根据块的宽度,我相应地设置了

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

    你的小提琴中有很多无关的CSS;如果可以的话,它可能有助于简化它。如果您仔细查看,
    每次调用。代码没有运行,因为它的语法不正确。@Cameron-Gah!谢谢。你的小提琴里有很多无关的CSS;如果可以的话,它可能有助于简化它。如果您仔细查看,
    每次调用。代码没有运行,因为它的语法不正确。@Cameron-Gah!谢谢你,聪明。如果按钮具有一致的宽度,这将起作用,但它可能会改变。聪明。如果按钮具有一致的宽度,这将起作用,但它可能会改变。