JQuery拉伸按钮水平到窗口宽度

时间:2013-05-29 16:22:51

标签: javascript jquery html css stretch

我尝试创建一个菜单,将其项目拉伸到窗口宽度。有人可以告诉我我做错了什么吗?我知道之前已经问过这个问题,但我不知道我的代码有什么问题。

这就是我想要实现的目标。红色是窗口

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>

提前致谢。

3 个答案:

答案 0 :(得分:2)

您的jQuery代码中有几处错误。您需要使用width()而不是width,因为它是一个函数调用。另外,在分配count时,您不是在选择菜单项,而是仅选择#menu

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

您还需要在主播上设置display:inline-blockdisplay:block,以便影响width

a { display:inline-block; }

Updated Fiddle

注意:您还需要在菜单项上考虑填充等,以获得正确的结果。

答案 1 :(得分:2)

这可以使用纯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;
}

此方法需要知道有多少列表项。

答案 2 :(得分:1)

使用$(“#menu”)。长度,您将获得#menu元素的出现次数 - 1.您应该使用以下内容来获取菜单项的数量

var count = $("#menu li").length;
相关问题