0

I try to create a menu that streches its items to the window width. Could someone please tell me what I'm doing wrong? I know that this question has been asked before but I just don't know what's wrong with my code.

This is what I"m trying to achieve. The red is the window

http://jsfiddle.net/JdGeQ/5/

Javascript

$(function(){
    $(window).resize(function (e) {
        setTimeout(function () {
            resizeButtons();
        }, 200);
    });
    resizeButtons();
});

function resizeButtons() {
    var count = $("#menu").length;
    var itemwidth = $(window).width / count;  

    $(".item").css("background", "blue");
    $(".item").css("width", itemwidth);
}

css

.elementtop {
    position: fixed;
    top: 0;
}
.elementfooter {
    position: fixed;
    bottom: 0;
}
.elementright {
    right: 0;
}
ul {
    min-width:100%;
    padding:0;
    margin:0;
    float:left;
    list-style-type:none;
    background: #000000;
}
li {
    display:inline;
}
a {
    overflow: hidden;
    text-decoration:none;
    color:white;
    background-color:purple;
    padding:0.2em 0.6em;
    border-right:1px solid white;
}

html

<div>
    <ul id="menu">
        <li>    <a href="#" class="item">
                <span>Text text</span>
            </a>

        </li>
        <li>    <a href="#" class="item">
                <span>Text2</span>
            </a>

        </li>
        <li>    <a href="#" class="item">
                <span>Text3</span>
            </a>

        </li>
    </ul>
</div>

Thanks in advance.

4

3 回答 3

2

You have a couple errors in your jQuery code. You need to use width() instead of width, as it is a function call. Also, you are not selecting menu items when you assign count, you are only selecting the #menu.

function resizeButtons() {
    var count = $("#menu .item").length;
    var itemwidth = $(window).width();
    itemwidth = itemwidth / count;  
    $(".item").css(
       "width", itemwidth  
    );
}

You also need to set display:inline-block or display:block on your anchors, so that you can affect the width.

a { display:inline-block; }

Updated Fiddle

Note: You will also need to account for the padding, etc. on your menu items to get the proper result.

于 2013-05-29T16:34:05.700 回答
2

This can be done with pure CSS:

http://cssdeck.com/labs/hgmvgwqc

ul {
    min-width:100%;
    padding:0;
    margin:0;
    display: table;
    list-style-type:none;
    background: #000000;
}
li {
    display: table-cell;
    width: 33%;
}
a {
    overflow: hidden;
    text-decoration:none;
    color:white;
    background-color:purple;
    padding:0.2em 0.6em;
    border-right:1px solid white;
    display: block;
}

This method requires knowing how many list items there are.

于 2013-05-29T16:51:14.787 回答
1

With $("#menu").length you're getting the number of occurrences of the #menu element -- 1. You should use the following to get the number of menu items

var count = $("#menu li").length;
于 2013-05-29T16:33:20.257 回答