我正在尝试创建一个字体选择器。在Firefox上一切正常,但在chrome上,选择框的更改事件不会调用select函数。
这是小提琴http://jsfiddle.net/y8ppa4zc/3/
代码就像这样
(function( $ ) {
var settings;
var methods = {
init : function(options) {
settings = $.extend( {
'hide_fallbacks' : false,
'selected' : function(style) {},
'initial' : '',
'fonts' : []
}, options);
var root = this;
root.callback = settings['selected'];
var visible = false;
var selected = false;
var displayName = function(font) {
if (settings['hide_fallbacks'])
return font.substr(0, font.indexOf(','));
else
return font;
}
var select = function(font) {
//root.append('<option value="'+displayName(font).replace(/["']{1}/gi,"")+'">'+displayName(font).replace(/["']{1}/gi,"")+ '</option>');
//root.css('font-family', font);
selected = font;
root.callback(selected);
}
// Setup markup
$(this).append('<option value="'+settings['initial'].replace(/'/g,''')+'">' + settings['initial'].replace(/'/g,''') + '</option>');
for (var i = 0; i < settings['fonts'].length; i++) {
var item = $('<optgroup><option value="'+displayName(settings['fonts'][i])+'">' + displayName(settings['fonts'][i]) + '</option></optgroup>').appendTo(this);
$(item).css('font-family', settings['fonts'][i]);
}
if (settings['initial'] != '')
select(settings['initial']);
$(this).click(function() {
//select($(this).val());
});
$(this).change(function(event) {
select($(this).val());
});
},
selected : function() {
return $(this).val();
},
select : function(font) {
font = $(this).val();
selected = font;
}
};
$.fn.fontSelector = function(method) {
if ( methods[method] ) {
return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
} else if ( typeof method === 'object' || ! method ) {
return methods.init.apply( this, arguments );
} else {
$.error( 'Method ' + method + ' does not exist on jQuery.fontSelector' );
}
}
}) ( $ );
$('#fontSelect').fontSelector({
'hide_fallbacks' : true,
'initial' : 'Courier New,Courier New,Courier,monospace',
'selected' : function(style) { alert("S1: " + style); },
'fonts' : [
'Arial,Arial,Helvetica,sans-serif',
'Arial Black,Arial Black,Gadget,sans-serif',
'Comic Sans MS,Comic Sans MS,cursive',
'Courier New,Courier New,Courier,monospace',
'Georgia,Georgia,serif',
'Impact,Charcoal,sans-serif',
'Lucida Console,Monaco,monospace',
'Lucida Sans Unicode,Lucida Grande,sans-serif',
'Palatino Linotype,Book Antiqua,Palatino,serif',
'Tahoma,Geneva,sans-serif',
'Times New Roman,Times,serif',
'Trebuchet MS,Helvetica,sans-serif',
'Verdana,Geneva,sans-serif',
'Gill Sans,Geneva,sans-serif'
]
});
HTML:
<div style="width:300px;margin:100px auto;">
<select id="fontSelect" class="fontSelect">
</select>
</div>