问题
I have modified JQuery Mobile NAVBAR to show bottom up navigation menu (instead of the standard drop down). As you can see from the code, I had to manually write css for every li node. For example, bottom:100% , bottom:200%, width: 25% etc... This is working but is there a way how to modify this css and create automatic bottom and width calculation when adding submenus?
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.1/jquery.mobile-1.4.1.min.css">
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.1/jquery.mobile-1.4.1.min.js"></script>
<style type="text/css">
#pageone > div.ui-content
{
padding-top:200px;
}
#pageone > div.ui-content > div > ul > li.ui-block-d > ul:nth-child(4)
{
bottom: 300%;
position:absolute;
width:25%;
}
#pageone > div.ui-content > div > ul > li.ui-block-d > ul:nth-child(3)
{
bottom: 200%;
position:absolute;
width:25%;
}
#pageone > div.ui-content > div > ul > li.ui-block-d > ul:nth-child(2)
{
bottom: 100%;
position:absolute;
width:25%;
}
</style>
</head>
<body>
<div data-role="page" id="pageone">
<div data-role="header">
<h1>Welcome To My Homepage</h1>
</div>
</br>
</br>
</br>
</br>
</br>
<div data-role="main" class="ui-content">
<div data-role="navbar">
<ul>
<li><a href="#" data-icon="plus">Btn1</a></li>
<li><a href="#" data-icon="plus">Btn2</a></li>
<li><a href="#" data-icon="plus">Btn3</a></li>
<li><a href="#" data-icon="minus">More</a>
<ul>
<li><a href="#" data-icon="minus">Test 1</a>
</ul>
<ul>
<li><a href="#" data-icon="minus">Test 2</a>
</ul>
<ul>
<li><a href="#" data-icon="minus">Test 3</a>
</ul>
</li>
</ul>
</div>
</div>
</div>
</body>
</html>
回答1:
It is pretty easy to do this with javascript/jQuery by looping through items and setting the CSS.
For convenience, I have given the navbar an id of theNavbar. In the following function we first get the top level nav items $("#theNavbar > ul > li"). The width in percent of any submenu we find will then be 100 divided by the number of items. Next we loop through all the top level items and see if we find submenu items $(this).find("ul"). If we do, we loop through the submenu items and set their CSS. the bottom css of each item is calculated as the index of the item plus 1 (0-based index) times 100.
$(document).on("pagecreate", "#pageone", function(){
var navItems = $("#theNavbar > ul > li");
var subWidth = 100 / navItems.length;
$("#theNavbar > ul > li").each(function( index ) {
$(this).find("ul").each(function(i) {
var bottom = (i + 1) * 100;
$(this).css({"position": "absolute",
"width": subWidth + "%",
"bottom": bottom + "%"});
});
});
});
Here is a DEMO
来源:https://stackoverflow.com/questions/21962418/how-to-make-css-for-navbar-jquery-mobile-bottom-up-submenu-automatic