开发者

jQuery <li>s sum width problem

I'm trying to make a submenu which looks like:

jQuery <li>s sum width problem

HTML:

<ul class="mainMenu clearfix">
    <li><a href="#">Eurodan huset</a></li>
    <li><a href="#">Hustyper</a></li>
    <li><a href="#">Galleri</a></li>
    <li><a href="#">10 byggesten</a></li>
    <li><a href="#">Huse til salg</a></li>
    <li><a href="#">Udstillinger</a>
        <ul class="underMenu">
            <li><a href="#">Salgskontorer</a></li>
            <li><a href="#">Velkommen</a></li>
            <li><a href="#">Historie</a></li>
            <li><a href="#">Fremtidens boliger</a></li>
        </ul>
    </li>
    <li><a href="#">Grunde</a></li>
    <li><a href="#">Om os</a></li>
    <li><a href="#">Katalog</a></li>
</ul>

Where .mainMenu is the big menu and .underMenu is a list with "underpages" from main menu. To make the under menu works I need a fixed width for it (it has position absolute and the <li> parent has position:relative so I make it using jquery.

jQuery/JavaScript:

$('.underMenu').each(function() {
    var t = $(this),
        tW = 0;

    $('li', t).each(function() {
        tW += $(this).outerWidth(true);
    });

    t.css('width', tW);

});

Following code above, my under menu should looks ok (the way I think) but the problem is that it looks like this:

jQuery <li>s sum width problem

To make it to wo开发者_JAVA百科rk I need to add 40px more to the width of .underMenu, but I can't understand where the problem is since I use $(this).outerWidth(true);.

According to my thinking everything should work ok but as you can see, it doesn't.

CSS:

.mainMenu,
.underMenu {
    clear:both;
    line-height:29px;
    background:url(../images/transPxBlack.png) repeat left top;
    -moz-border-radius:16px;
    -webkit-border-radius: 16px;
    border-radius:16px;
    padding:0 20px;
}
.mainMenu > li {
    margin-left:16px;
    position:relative;
    font-size:13px;
}
.mainMenu > li:first-child {margin-left:0;}

.underMenu {position:absolute;}
.underMenu li {
    font-size:11px;
    margin-left:18px;
}
.underMenu li:first-child {margin-left:0;}


Your width calculation is working at the sum of the width of the child li tags, but it isn't accounting for the padding on the .underMenu so your overall width comes up short. If you add the padding in, it works:

$('.underMenu').each(function(){
    var t = $(this),
        tW = 0;

    $('li', t).each(function(){
        tW += $(this).outerWidth(true);
    });

    t.css('width', tW + t.outerWidth(true) - t.width());
});

You can see it here: http://jsfiddle.net/jfriend00/CTuz3/


Your calculation is workiong fine. Add display:inline-block and float:left to .underMenu li rule you will see as expected.

            .underMenu li {
                font-size:11px;
                margin-left:18px;
                display:inline-block;
                float:left;
            }

Working demo

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜