jQuery Font Selector: show&hide with focus
I'm trying to implement a jQuery Font Selector in my project but I have some troubles to achieve it. I'm using the source code I found here jQuery Font Selector You can see the demo here
Everything is working great, except the author of this code hasn't included a function that close the "scrolling menu" if we clicked anywhere else on the screen. You're forced to choose something inside that list for this list to close.
I'm going to paste the code here so it'll be easier to explain.
/**
* Font selector plugin
*/
jQuery.fn.fontSelector = function() {
var fonts = new Array(
'Arial,Arial,Helvetica,sans-serif',
'Arial Black,Arial Black,Gadget,sans-serif',
/* other fonts */);
return this.each(function(){
// Get input field
var sel = this;
// Add a ul to hold fonts
var ul = $('<ul class="fontselector"></ul>');
$('body').prepend(ul);
$(ul).hide();
jQuery.each(fonts, function(i, item) {
$(ul).append('<li><a href="#" class="font_' + i + '" style="font-family: ' + item + '">' + item.split(',')[0] + '</a></li>');
// Prevent real select from working
$(sel).focus(function(ev) {
ev.preventDefault();
// Show font list
$(ul).show();
// Position font list
$(ul).css({ top: $(sel).offset().top + $(sel).height() + 4,
left: $(sel).offset().left});
// Blur field
$(this).blur();
return false;
});
$(ul).find('a').click(function() {
var font = fonts[$(this).attr('class').split('_')[1]];
$(sel).val(font);
$(ul).hide();
return false;
});
});
});
}
From here I tried to modify the code, like adding $(ul).hide();
inside the blur function... Works BUT that i don't want the input to be manually editable. I don't want the user to be able to modify the content of the input except by selecting a font.
I hope you're not to confused with what I'm asking !
Thanks开发者_运维技巧 for your help
EDIT: Some changes after discussion:
http://jsfiddle.net/ahkEv/4/
Add the following inside jQuery.fn.fontSelector = function() {
$("body").click(function(){
$(".fontselector").hide();
});
Change $(sel).focus
to
$(sel).click(function(ev) {
and add the following to $(ul).find('a').click(function(ev) {
ev.stopPropagation();
精彩评论