I have a UL LI menu that I am turning into a select dropdown when you're viewing it on a mobile.
I want to now indent child items e.g
- List item 1
- -- Child item 1
- ---- Child Child item 1
- -- Child item 2
- List item 2
Rather than listing in one single line.
I'm happy to just add nbsp to keep things easy - or add classes and CSS if more suitable.
The code I am currently using to generate the select is:
$("<select />").appendTo("#primary-nav");
$("<option />", {
"selected": "selected",
"value" : "",
"text" : "Go to..."
}).appendTo("#primary-nav select");
$("#primary-nav a").each(function() {
var el = $(this);
$("<option />", {
"value" : el.attr("href"),
"text" : el.text()
}).appendTo("#primary-nav select");
});
$("#primary-nav select").change(function() {
window.location = $(this).find("option:selected").val();
});
The menu it is generating from is built like:
<ul>
<li><a>Item 1</a>
<ul>
<li><a>Child Item 1</a>
<ul>
<li><a>Child Item 1</a></li>
</ul>
</li>
<li><a>Child Item 2</a></li>
</ul>
</li>
<li><a>Item 2</a></li>
</ul>
Here is a fiddle with an example: http://jsfiddle.net/C5S32/
This should do what you want, and it's pretty customizable. http://jsfiddle.net/C5S32/7/
var options = '<option selected>Go to...</option>';
$('#primary-nav').find('a').each(function () {
var text = $(this).text(),
depth = $(this).parent().parents('ul').length,
depthChar = '',
i = 1;
for (i; i < depth; i++) { depthChar += '– '; }
options += '<option>' + depthChar + text + '</option>';
});
$('<select />').append(options).appendTo('#primary-nav');
As a side note, in your code you're appending stuff many times. It's better to append everything in one call to avoid excessive reflows.
This should do it, Not sure about support for "margin-left" on mobiles but will point you in the right direction.
EDIT: Seems only Firefox allows margin on option elements,
See if this suits your needs:
I just added this:
li {
padding-left: 1em;
}
Best Solution that I found adds child indented "-" marks automatically. Make sure that you change the top ".navbar .nav" to your own div class or id that is setup on the original ul.
来源:https://stackoverflow.com/questions/9358148/create-select-from-list-indent-child-items