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
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.
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; }
Note: You will also need to account for the padding, etc. on your menu items to get the proper result.
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.
使用$(“#menu”)。length,您可以获取#menu元素的出现次数-1.您应使用以下命令获取菜单项的数量
var count = $("#menu li").length;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.