Applying a style to and inserting a line break after the first word in a link
I've been asked to recreate an HTML site in WordPres开发者_开发技巧s and have it all done except for a meny bar that has me stumped. See image at: http://img36.imageshack.us/img36/8964/menubare.jpg
In short, I need a way to stylize the first word of an element differently than the rest of it and insert a line break following that first word. I'm sure it's a quick jQuery hack, but don't know enough about jQ to make it happen on my own.
Here's the catch: Those little arrows signal a drop-down menu shows up. I have the dropdowns working, but want to make sure whatever solution applies to the main menu, skips the dropdown ones (They're UL lists within an LI item).
Any help would be appreciated.
$('#nav').children('li').find('a').each(function(){
var old = $(this).text();
$(this).html(old.substring(0,old.indexOf(' ')) +'<br/>'+old.substring(old.indexOf(' '),old.length));
});
if you need to apply some class
$(this).html('<span class="first">'+old.substring(0,old.indexOf(' ')) +'</span><br/><span class="next">'+old.substring(old.indexOf(' '),old.length)+"</span>");
Without an HTML example of your menu, its hard to give you a specific answer.
But you could use some jQuery like the following, it will allow you to add styling to the first word, and the rest of them. It will .split()
the HTML on spaces, giving you an array. Wrap the first item in a span allowing styling. Then uses jQuery's .each()
to loop through the rest of the items adding them back to the string. Then replaces the HTML with the new version:
$('#header > ul.nav > li > a').each(function() {
var obj = $(this);
var text = obj.html();
var parts = text.split(' ');
var replace = '<span class="firstWord">'+parts[0]+'</span><br />';
parts.shift();
$.each(parts, function(key, value) {
replace += ' '+value;
});
obj.html(replace);
});
Example CSS:
.firstWord {
font-size: 15px;
}
.menuHeader {
margin-left: 10px;
float: left;
font-size: 40px;
}
.menu {
width: 100%;
height: 120px;
background-color: #FF8C00;
}
Take a look at a working demo
Update to the demo reflect code from comment.
Use the selector:
$('#header > ul.nav > li > a')
To select only the first menu item. You should only need to add:
.firstWord {
font-size: 15px;
}
To your CSS to adjust the size of the first item.
Good suggestion by Edwin V., you could change the jQuery to:
$('#header > ul.nav > li > a').each(function() {
var obj = $(this);
var text = obj.html();
var parts = text.split(' ');
var replace = '<span class="firstWord">'+parts[0]+'</span><br />';
parts.shift();
replace += parts.join(' ');
obj.html(replace);
});
To shorten it a little. Demo here..
精彩评论