问题
I need to have a menu that has items that size themselves based on how many there are. Say, there are three items. Each one would have about 33% width of the container. But if there were were ten, each would have 10%. Does anyone have any ideas/suggestions? Thanks!
回答1:
Usually menu is built from unordered list and parent menu element have id="menu" In this case you'll need code like next:
menuElt = document.getElementById('menu');
childElements = menuElt.getElementsByTagName("li");
var quantity = childElements.length;
var widthPercent = Math.round(100/quantity);
for (var i = 0; i < quantity; i++) {
childElements[i].style.width = widthPercent + "%";
}
来源:https://stackoverflow.com/questions/4988813/size-menu-items-based-on-how-many-there-are-in-js