簡體   English   中英

jQuery拉伸按鈕水平到窗口寬度

[英]JQuery stretch buttons horizontal to window width

我嘗試創建一個菜單,將該菜單項拉長到窗口寬度。 有人可以告訴我我在做什么錯嗎? 我知道已經問過這個問題了,但是我不知道我的代碼有什么問題。

這就是我要實現的目標。紅色是窗口

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>

提前致謝。

您的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; }

更新小提琴

注意:您還需要考慮菜單項上的填充等,以獲得正確的結果。

這可以通過純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;
}

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

使用$(“#menu”)。length,您可以獲取#menu元素的出現次數-1.您應使用以下命令獲取菜單項的數量

var count = $("#menu li").length;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM