$(function(){ $('body').on('click','.comp_selec',function(){ openSelecOptions($(this).find('.sel_con>input')); }); $('body').on('click',function(e){ if(!$(e.target).isMembers($('.comp_selec,.comp_selec *,.comp_selec_options,.comp_selec_options *'))){ $('.comp_selec[state="running"]').each(function(){ $(this).data('close')(); }); } }); function closeSelecOptions(){ $('.comp_selec_options').each(function(){ $(this).fadeOut(function(){ $(this).remove(); }); }); } function openSelecOptions($t){ var $selec = $t.parents('.comp_selec').eq(0); var ofs = $t.offset(); var left = ofs.left - 1; var top = ofs.top + $t.height() + 1; var width = $t.outerWidth() + 2; $('.comp_selec[state="running"]').each(function(){ $(this).data('close')(); }); var oldVal = $t.val(); var needVal = oldVal; $t.val(''); $t.trigger('focus'); $t.val(needVal); var arr = []; $t.parents('.comp_selec').find('.option>a').each(function(){ var obj = {}; obj.val = $(this).data('value'); obj.name = $(this).html(); arr.push(obj); }); var $options = $('
'); arr.forEach(function(item){ $options.append(''+item.val+'') }); $options .appendTo($('body')) .css({ "position": 'absolute', "width": width, 'display': 'none', "z-index": 10000 }) .offset({ top: top, left: left }) .fadeIn(50); var search = function(){ var val = $(this).val(); var newArr = filterArr(val); $options.html(''); newArr.forEach(function(item){ $options.append(''+item.val+'') }); if(newArr.length == 0){ $options.append('
没检索到结果
') }; } var close = function(){ $t.val(needVal); $options.remove(); $selec.attr('state','stop'); $selec.data('close',function(){}); if(oldVal != needVal){ $t.trigger('selected'); } $options = null; needVal = null; oldVal = null; } $t.off('input'); $t.off('propertychange'); $t.on('input',search); $t.on('propertychange',search); $options.on('click','>a',function(){ needVal = $(this).html(); $t.val(needVal); close(); }); function filterArr(val){ var patt = new RegExp(val); return arr.filter(function(item){ return patt.test(item.val)||patt.test(pinyin.getFullChars(item.val).toLowerCase()); }); } $selec.attr('state','running'); $selec.data('close',close); }; })