http://www.17sucai.com/pins/23021.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>jquery autocomplete类似百度搜索框自动提示插件</title> <style type="text/css"> /** * Common */ body { /* Pattern made by Atle Mo. */ background-image: url('http://www.17sucai.com/preview/169662/2017-02-09/jquery%E7%B1%BB%E4%BC%BC%E7%99%BE%E5%BA%A6%E6%90%9C%E7%B4%A2%E8%87%AA%E5%8A%A8%E5%AE%8C%E6%88%90%E6%8F%92%E4%BB%B6autocompleter/img/bcg.png'); font-family: 'Helvetica', 'Arial', sans-serif; text-align: center; color: #ffffff; } main { width: 600px; margin: 40px auto; } h1 { font-size: 58px; } hr { width: 50%; border: 0; height: 1px; margin: 40px auto; background: #4d4d4d; } a { color: #777; } p { color: #c8c7c7; font-size: 20px; line-height: 24px; } /** * Custom */ p.caption { color: #ccc; font-size: 16px; } .button { margin: 20px auto; display: inline-block; padding: 16px 40px; background: #70b3eb; text-decoration: none; font-size: 30px; color: #ffffff; text-shadow: 0px -1px 1px rgba(26, 62, 103, 0.42); box-shadow: inset 0 0 0 1px #70b3eb, inset 0 1px 0 1px rgba(255,255,255,0.5); border-radius: 5px; -webkit-transition: 0.2s ease -webkit-transform; -moz-transition: 0.2s ease -moz-transform; transition: 0.2s ease transform; } .button:hover { -webkit-transform: translateY(-3px); -moz-transform: translateY(-3px); transform: translateY(-3px); } .field { position: relative; } .field input { width: 100%; -webkit-box-sizing: border-box; box-sizing: border-box; color: #000000; height: 60px; font-size: 24px; padding: 0 12px; border: 0; } .field input:focus { outline: 0; } .icon { position: absolute; right: 0; top: 0; width: 60px; height: 60px; background-image: url('http://www.17sucai.com/preview/169662/2017-02-09/jquery%E7%B1%BB%E4%BC%BC%E7%99%BE%E5%BA%A6%E6%90%9C%E7%B4%A2%E8%87%AA%E5%8A%A8%E5%AE%8C%E6%88%90%E6%8F%92%E4%BB%B6autocompleter/img/icon.png'); background-color: #ffffff; } /** * Simplecomplete */ .autocompleter { width: 100%; background: #dddddd; position: absolute; top: 60px; left: 0; z-index: 100; } .autocompleter, .autocompleter-hint { position: absolute; } .autocompleter-list { box-shadow: inset 0px 0px 6px rgba(0,0,0,0.1); list-style: none; margin: 0; padding: 0; text-align: left; -webkit-box-sizing: border-box; box-sizing: border-box; } .autocompleter-item-selected { background: #ffffff; } .autocompleter-item { padding: 6px 12px; color: #444444; font-size: 20px; cursor: pointer; } .autocompleter-item:hover { background: #dbed8a; } .autocompleter-item strong { background: #f9de8f; text-shadow: 0 1px 0 #ffffff; } .autocompleter-item span { color: #bbbbbb; } .autocompleter-hint { color: #ccc; text-align: left; top: -56px; font-weight: 400; left: 0; width: 100%; padding: 12px 12px 12px 13px; font-size: 24px; display: none; } .autocompleter-hint span { color: transparent; } .autocompleter-hint-show { display: block; } .autocompleter-closed { display: none; } </style> <body> <main> <h1>jQuery Autocompleter</h1> <hr /> <div class="field"> <div class="icon"></div> <input type="text" name="nope" id="nope" placeholder="Crayola colors" maxlength="40" /> </div> </main> </body> <script src="http://cdn.bootcss.com/jquery/1.11.0/jquery.min.js"></script> <script type="text/javascript"> /* * jquery-autocompleter v0.1.10 - 2015-01-22 * Simple, easy, customisable and with localStorage cache support. * http://github.com/ArtemFitiskin/jquery-autocompleter * * Copyright 2015 Artem Fitiskin; MIT Licensed */ ;(function ($, window) { 'use strict'; var guid = 0, ignoredKeyCode = [9, 13, 17, 19, 20, 27, 33, 34, 35, 36, 37, 39, 44, 92, 113, 114, 115, 118, 119, 120, 122, 123, 144, 145], allowOptions = [ 'source', 'empty', 'limit', 'cache', 'cacheExpires', 'focusOpen', 'selectFirst', 'changeWhenSelect', 'highlightMatches', 'ignoredKeyCode', 'customLabel', 'customValue', 'template', 'offset', 'combine', 'callback', 'minLength', 'delay' ], userAgent = (window.navigator.userAgent||window.navigator.vendor||window.opera), isFirefox = /Firefox/i.test(userAgent), isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(userAgent), isFirefoxMobile = (isFirefox && isMobile), $body = null, delayTimeout = null, localStorageKey = 'autocompleterCache', supportLocalStorage = (function () { var supported = typeof window.localStorage !== 'undefined'; if (supported) { try { localStorage.setItem('autocompleter', 'autocompleter'); localStorage.removeItem('autocompleter'); } catch (e) { supported = false; } } return supported; })(); /** * Don't forget update README.md * * @options * @param source [(string|object)] <null> "URL to the server or a local object" * @param asLocal [boolean] <false> "Parse remote response as local source" * @param empty [boolean] <true> "Launch if value is empty" * @param limit [int] <10> "Number of results to be displayed" * @param minLength [int] <0> "Minimum length for autocompleter" * @param delay [int] <0> "Few milliseconds to defer the request" * @param customClass [array] <[]> "Array with custom classes for autocompleter element" * @param cache [boolean] <true> "Save xhr data to localStorage to avoid the repetition of requests" * @param cacheExpires [int] <86400> "localStorage data lifetime" * @param focusOpen [boolean] <true> "Launch autocompleter when input gets focus" * @param hint [boolean] <false> "Add hint to input with first matched label, correct styles should be installed" * @param selectFirst [boolean] <false> "If set to true, first element in autocomplete list will be selected automatically, ignore if changeWhenSelect is on" * @param changeWhenSelect [boolean] <true> "Allows to change input value using arrow keys navigation in autocomplete list" * @param highlightMatches [boolean] <false> "This option defines <strong> tag wrap for matches in autocomplete results" * @param ignoredKeyCode [array] <[]> "Array with ignorable keycodes" * @param customLabel [boolean] <false> "The name of object's property which will be used as a label" * @param customValue [boolean] <false> "The name of object's property which will be used as a value" * @param template [(string|boolean)] <false> "Custom template for list items" * @param offset [(string|boolean)] <false> "Source response offset, for example: response.items.posts" * @param combine [function] <$.noop> "Returns an object which extends ajax data. Useful if you want to pass some additional server options" * @param callback [function] <$.noop> "Select value callback function. Arguments: value, index" */ var options = { source: null, asLocal: false, empty: true, limit: 10, minLength: 0, delay: 0, customClass: [], cache: true, cacheExpires: 86400, focusOpen: true, hint: false, selectFirst: false, changeWhenSelect: true, highlightMatches: false, ignoredKeyCode: [], customLabel: false, customValue: false, template: false, offset: false, combine: $.noop, callback: $.noop }; var publics = { /** * @method * @name defaults * @description Sets default plugin options * @param opts [object] <{}> "Options object" * @example $.autocompleter('defaults', opts); */ defaults: function (opts) { options = $.extend(options, opts || {}); return (typeof this === 'object') ? $(this) : true; }, /** * @method * @name option * @description Open autocompleter list */ option: function (properties) { return $(this).each(function (i, input) { var data = $(input).next('.autocompleter').data('autocompleter'); for (var property in properties) { if ($.inArray(property, allowOptions) !== -1) { data[property] = properties[property]; } } }); }, /** * @method * @name open * @description Open autocompleter list */ open: function () { return $(this).each(function (i, input) { var data = $(input).next('.autocompleter').data('autocompleter'); if (data) { _open(null, data); } }); }, /** * @method * @name close * @description Close autocompleter list */ close: function () { return $(this).each(function (i, input) { var data = $(input).next('.autocompleter').data('autocompleter'); if (data) { _close(null, data); } }); }, /** * @method * @name clearCache * @description Remove localStorage cache */ clearCache: function () { _deleteCache(); }, /** * @method * @name destroy * @description Removes instance of plugin * @example $('.target').autocompleter('destroy'); */ destroy: function () { return $(this).each(function (i, input) { var data = $(input).next('.autocompleter').data('autocompleter'); if (data) { // Abort xhr if (data.jqxhr) { data.jqxhr.abort(); } // If has selected item & open - confirm it if (data.$autocompleter.hasClass('open')) { data.$autocompleter.find('.autocompleter-selected') .trigger('click.autocompleter'); } // Restore original autocomplete attr if (!data.originalAutocomplete) { data.$node.removeAttr('autocomplete'); } else { data.$node.attr('autocomplete', data.originalAutocomplete); } // Remove autocompleter & unbind events data.$node.off('.autocompleter') .removeClass('autocompleter-node'); data.$autocompleter.off('.autocompleter') .remove(); } }); } }; /** * @method private * @name _init * @description Initializes plugin * @param opts [object] "Initialization options" */ function _init(opts) { // Local options opts = $.extend({}, options, opts || {}); // Check for Body if ($body === null) { $body = $('body'); } // Apply to each element var $items = $(this); for (var i = 0, count = $items.length; i < count; i++) { _build($items.eq(i), opts); } return $items; } /** * @method private * @name _build * @description Builds each instance * @param $node [jQuery object] "Target jQuery object" * @param opts [object] <{}> "Options object" */ function _build($node, opts) { if (!$node.hasClass('autocompleter-node')) { // Extend options opts = $.extend({}, opts, $node.data('autocompleter-options')); // Check for as local or .json file if (typeof opts.source === 'string' && (opts.source.slice(-5) === '.json' || opts.asLocal === true)) { $.ajax({ url: opts.source, type: 'GET', dataType: 'json', async: false }).done(function (response) { opts.source = response; }); } var html = '<div class="autocompleter ' + opts.customClass.join(' ') + '" id="autocompleter-' + (guid + 1) + '">'; if (opts.hint) { html += '<div class="autocompleter-hint"></div>'; } html += '<ul class="autocompleter-list"></ul>'; html += '</div>'; $node.addClass('autocompleter-node') .after(html); var $autocompleter = $node.next('.autocompleter').eq(0); // Set autocomplete to off for warn overlay var originalAutocomplete = $node.attr('autocomplete'); $node.attr('autocomplete', 'off'); // Store plugin data var data = $.extend({ $node: $node, $autocompleter: $autocompleter, $selected: null, $list: null, index: -1, hintText: false, source: false, jqxhr: false, response: null, focused: false, query: '', originalAutocomplete: originalAutocomplete, guid: guid++ }, opts); // Bind autocompleter events data.$autocompleter.on('mousedown.autocompleter', '.autocompleter-item', data, _select) .data('autocompleter', data); // Bind node events data.$node.on('keyup.autocompleter', data, _onKeyup) .on('keydown.autocompleter', data, _onKeydown) .on('focus.autocompleter', data, _onFocus) .on('blur.autocompleter', data, _onBlur) .on('mousedown.autocompleter', data, _onMousedown); } } /** * @method private * @name _search * @description Local search function, return best collation * @param query [string] "Query string" * @param source [object] "Source data" * @param data [object] "Instance data" */ function _search(query, source, data) { var response = []; query = query.toUpperCase(); if (source.length) { for (var i = 0; i < 2; i++) { for (var item in source) { if (response.length < data.limit) { var label = (data.customLabel && source[item][data.customLabel]) ? source[item][data.customLabel] : source[item].label; switch (i) { case 0: if (label.toUpperCase().search(query) === 0) { response.push(source[item]); delete source[item]; } break; case 1: if (label.toUpperCase().search(query) !== -1) { response.push(source[item]); delete source[item]; } break; } } } } } return response; } /** * @method private * @name _launch * @description Launch autocompleter * @param data [object] "Instance data" */ function _launch(data) { // Clear previous timeout clearTimeout(delayTimeout); data.query = $.trim(data.$node.val()); if ((!data.empty && data.query.length === 0) || (data.minLength && (data.query.length < data.minLength))) { _clear(data); return; } if (data.delay) { // Be careful: delay used also with local source delayTimeout = setTimeout(function () { _xhr(data); }, data.delay); } else { _xhr(data); } } /** * @method private * @name _xhr * @description Use source locally or create xhr * @param data [object] "Instance data" */ function _xhr(data) { if (typeof data.source === 'object') { _clear(data); // Local search var search = _search(data.query, _clone(data.source), data); if (search.length) { _response(search, data); } } else { if (data.jqxhr) { data.jqxhr.abort(); } var ajaxData = $.extend({ limit: data.limit, query: data.query }, data.combine(data.query)); data.jqxhr = $.ajax({ url: data.source, dataType: 'json', crossDomain: true, data: ajaxData, beforeSend: function (xhr) { data.$autocompleter.addClass('autocompleter-ajax'); _clear(data); if (data.cache) { var stored = _getCache(this.url, data.cacheExpires); if (stored) { xhr.abort(); _response(stored, data); } } } }) .done(function (response) { // Get subobject from responce if (data.offset) { response = _grab(response, data.offset); } // Set cache if (data.cache) { _setCache(this.url, response); } _response(response, data); }) .always(function () { data.$autocompleter.removeClass('autocompleter-ajax'); }); } } /** * @method private * @name _clear * @param data [object] "Instance data" */ function _clear(data) { // Clear data data.response = null; data.$list = null; data.$selected = null; data.index = 0; data.$autocompleter.find('.autocompleter-list').empty(); data.$autocompleter.find('.autocompleter-hint').removeClass('autocompleter-hint-show').empty(); data.hintText = false; _close(null, data); } /** * @method private * @name _response * @description Main source response function * @param response [object] "Source data" * @param data [object] "Instance data" */ function _response(response, data) { _buildList(response, data); if (data.$autocompleter.hasClass('autocompleter-focus')) { _open(null, data); } } /** * @method private * @name _buildList * @description Generate autocompleter-list and update instance data by source * @param list [object] "Source data" * @param data [object] "Instance data" */ function _buildList(list, data) { var menu = ''; for (var item = 0, count = list.length; item < count; item++) { var classes = ['autocompleter-item'], highlightReg = new RegExp(data.query, 'gi'); if (data.selectFirst && item === 0 && !data.changeWhenSelect) { classes.push('autocompleter-item-selected'); } var label = (data.customLabel && list[item][data.customLabel]) ? list[item][data.customLabel] : list[item].label, clear = label; label = data.highlightMatches ? label.replace(highlightReg, '<strong>$&</strong>') : label; var value = (data.customValue && list[item][data.customValue]) ? list[item][data.customValue] : list[item].value; // Apply custom template if (data.template) { var template = data.template.replace(/({{ label }})/gi, label); for (var property in list[item]) { if (list[item].hasOwnProperty(property)) { var regex = new RegExp('{{ ' + property + ' }}', 'gi'); template = template.replace(regex, list[item][property]); } } label = template; } if (value) { menu += '<li data-value="' + value + '" data-label="' + clear + '" class="' + classes.join(' ') + '">' + label + '</li>'; } else { menu += '<li data-label="' + clear + '" class="' + classes.join(' ') + '">' + label + '</li>'; } } // Set hint if (list.length && data.hint) { var hintLabel = (data.customLabel && list[0][data.customLabel]) ? list[0][data.customLabel] : list[0].label, hint = ( hintLabel.substr(0, data.query.length).toUpperCase() === data.query.toUpperCase() ) ? hintLabel : false; if (hint && (data.query !== hintLabel)) { var hintReg = new RegExp(data.query, 'i'); var hintText = hint.replace(hintReg, '<span>' + data.query + '</span>'); data.$autocompleter.find('.autocompleter-hint').addClass('autocompleter-hint-show').html(hintText); data.hintText = hintText; } } // Update data data.response = list; data.$autocompleter.find('.autocompleter-list').html(menu); data.$selected = (data.$autocompleter.find('.autocompleter-item-selected').length) ? data.$autocompleter.find('.autocompleter-item-selected') : null; data.$list = (list.length) ? data.$autocompleter.find('.autocompleter-item') : null; data.index = data.$selected ? data.$list.index(data.$selected) : -1; data.$autocompleter.find('.autocompleter-item').each(function (i, j) { $(j).data(data.response[i]); }); } /** * @method private * @name _onKeyup * @description Keyup events in node, up/down autocompleter-list navigation, typing and enter button callbacks * @param e [object] "Event data" */ function _onKeyup(e) { var data = e.data, code = e.keyCode ? e.keyCode : e.which; if ( (code === 40 || code === 38) && data.$autocompleter.hasClass('autocompleter-show') ) { // Arrows up & down var len = data.$list.length, next, prev; if (len) { // Determine new index if (len > 1) { if (data.index === len - 1) { next = data.changeWhenSelect ? -1 : 0; prev = data.index - 1; } else if (data.index === 0) { next = data.index + 1; prev = data.changeWhenSelect ? -1 : len - 1; } else if (data.index === -1) { next = 0; prev = len - 1; } else { next = data.index + 1; prev = data.index - 1; } } else if (data.index === -1) { next = 0; prev = 0; } else { prev = -1; next = -1; } data.index = (code === 40) ? next : prev; // Update HTML data.$list.removeClass('autocompleter-item-selected'); if (data.index !== -1) { data.$list.eq(data.index).addClass('autocompleter-item-selected'); } data.$selected = data.$autocompleter.find('.autocompleter-item-selected').length ? data.$autocompleter.find('.autocompleter-item-selected') : null; if (data.changeWhenSelect) { _setValue(data); } } } else if ($.inArray(code, ignoredKeyCode) === -1 && $.inArray(code, data.ignoredKeyCode) === -1) { // Typing _launch(data); } } /** * @method private * @name _onKeydown * @description Keydown events in node, up/down for prevent cursor moving and right arrow for hint * @param e [object] "Event data" */ function _onKeydown(e) { var data = e.data, code = e.keyCode ? e.keyCode : e.which; if (code === 40 || code === 38 ) { e.preventDefault(); e.stopPropagation(); } else if (code === 39) { // Right arrow if (data.hint && data.hintText && data.$autocompleter.find('.autocompleter-hint').hasClass('autocompleter-hint-show')) { e.preventDefault(); e.stopPropagation(); var hintOrigin = data.$autocompleter.find('.autocompleter-item').length ? data.$autocompleter.find('.autocompleter-item').eq(0).attr('data-label') : false; if (hintOrigin) { data.query = hintOrigin; _setHint(data); } } } else if (code === 13) { // Enter if (data.$autocompleter.hasClass('autocompleter-show') && data.$selected) { _select(e); } } } /** * @method private * @name _onFocus * @description Handles instance focus * @param e [object] "Event data" * @param internal [boolean] "Called by plugin" */ function _onFocus(e, internal) { if (!internal) { var data = e.data; data.$autocompleter.addClass('autocompleter-focus'); if (!data.$node.prop('disabled') && !data.$autocompleter.hasClass('autocompleter-show')) { if (data.focusOpen) { _launch(data); data.focused = true; setTimeout(function () { data.focused = false; }, 500); } } } } /** * @method private * @name _onBlur * @description Handles instance blur * @param e [object] "Event data" * @param internal [boolean] "Called by plugin" */ function _onBlur(e, internal) { e.preventDefault(); e.stopPropagation(); var data = e.data; if (!internal) { data.$autocompleter.removeClass('autocompleter-focus'); _close(e); } } /** * @method private * @name _onMousedown * @description Handles mousedown to node * @param e [object] "Event data" */ function _onMousedown(e) { // Disable middle & right mouse click if (e.type === 'mousedown' && $.inArray(e.which, [2, 3]) !== -1) { return; } var data = e.data; if (data.$list && !data.focused) { if (!data.$node.is(':disabled')) { if (isMobile && !isFirefoxMobile) { var el = data.$select[0]; if (window.document.createEvent) { // All var evt = window.document.createEvent('MouseEvents'); evt.initMouseEvent('mousedown', false, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null); el.dispatchEvent(evt); } else if (el.fireEvent) { // IE el.fireEvent('onmousedown'); } } else { // Delegate intent if (data.$autocompleter.hasClass('autocompleter-closed')) { _open(e); } else if (data.$autocompleter.hasClass('autocompleter-show')) { _close(e); } } } } } /** * @method private * @name _open * @description Opens option set * @param e [object] "Event data" * @param instanceData [object] "Instance data" */ function _open(e, instanceData) { var data = e ? e.data : instanceData; if (!data.$node.prop('disabled') && !data.$autocompleter.hasClass('autocompleter-show') && data.$list && data.$list.length) { data.$autocompleter.removeClass('autocompleter-closed').addClass('autocompleter-show'); $body.on('click.autocompleter-' + data.guid, ':not(.autocompleter-item)', data, _closeHelper); } } /** * @method private * @name _closeHelper * @description Determines if event target is outside instance before closing * @param e [object] "Event data" */ function _closeHelper(e) { if ( $(e.target).hasClass('autocompleter-node') ) { return; } if ($(e.currentTarget).parents('.autocompleter').length === 0) { _close(e); } } /** * @method private * @name _close * @description Closes option set * @param e [object] "Event data" * @param instanceData [object] "Instance data" */ function _close(e, instanceData) { var data = e ? e.data : instanceData; if (data.$autocompleter.hasClass('autocompleter-show')) { data.$autocompleter.removeClass('autocompleter-show').addClass('autocompleter-closed'); $body.off('.autocompleter-' + data.guid); } } /** * @method private * @name _select * @description Select item from .autocompleter-list * @param e [object] "Event data" */ function _select(e) { // Disable middle & right mouse click if (e.type === 'mousedown' && $.inArray(e.which, [2, 3]) !== -1) { return; } var data = e.data; e.preventDefault(); e.stopPropagation(); if (e.type === 'mousedown' && $(this).length) { data.$selected = $(this); data.index = data.$list.index(data.$selected); } if (!data.$node.prop('disabled')) { _close(e); _update(data); if (e.type === 'click') { data.$node.trigger('focus', [ true ]); } } } /** * @method private * @name _setHint * @description Set autocompleter by hint * @param data [object] "Instance data" */ function _setHint(data) { _setValue(data); _handleChange(data); _launch(data); } /** * @method private * @name _setValue * @description Set value for native field * @param data [object] "Instance data" */ function _setValue(data) { if (data.$selected) { if (data.hintText && data.$autocompleter.find('.autocompleter-hint').hasClass('autocompleter-hint-show')) { data.$autocompleter.find('.autocompleter-hint').removeClass('autocompleter-hint-show'); } data.$node.val(data.$selected.attr('data-value') ? data.$selected.attr('data-value') : data.$selected.attr('data-label')); } else { if (data.hintText && !data.$autocompleter.find('.autocompleter-hint').hasClass('autocompleter-hint-show')) { data.$autocompleter.find('.autocompleter-hint').addClass('autocompleter-hint-show'); } data.$node.val(data.query); } } /** * @method private * @name _update * @param data [object] "Instance data" */ function _update(data) { _setValue(data); _handleChange(data); _clear(data); } /** * @method private * @name _handleChange * @description Trigger node change event and call the callback function * @param data [object] "Instance data" */ function _handleChange(data) { data.callback.call(data.$autocompleter, data.$node.val(), data.index, data.response[data.index]); data.$node.trigger('change'); } /** * @method private * @name _grab * @description Grab sub-object from object * @param response [object] "Native object" * @param offset [string] "Offset string" */ function _grab(response, offset) { offset = offset.split('.'); while (response && offset.length) { response = response[offset.shift()]; } return response; } /** * @method private * @name _setCache * @description Store AJAX response in plugin cache * @param url [string] "AJAX get query string" * @param data [object] "AJAX response data" */ function _setCache(url, data) { if (!supportLocalStorage) { return; } if (url && data) { cache[url] = { value: data, timestamp: +new Date() }; // Proccess to localStorage try { localStorage.setItem(localStorageKey, JSON.stringify(cache)); } catch (e) { var code = e.code || e.number || e.message; if (code === 22) { _deleteCache(); } else { throw(e); } } } } /** * @method private * @name _getCache * @description Get cached data by url if exist * @param url [string] "AJAX get query string" */ function _getCache(url, expires) { var response = false, item; expires = expires || false; if (!url) { return false; } item = cache[url]; if (item && item.value) { response = item.value; if (item.timestamp && expires && (+new Date() - item.timestamp > expires * 1000)) { return false; } else { return response; } } else { return false; } } /** * @method private * @name _loadCache * @description Load all plugin cache from localStorage */ function _loadCache() { if (!supportLocalStorage) { return; } return JSON.parse(localStorage.getItem(localStorageKey) || '{}'); } /** * @method private * @name _deleteCache * @description Delete all plugin cache from localStorage */ function _deleteCache() { try { localStorage.removeItem(localStorageKey); cache = _loadCache(); } catch (e) { throw(e); } } /** * @method private * @name _clone * @description Clone JavaScript object */ function _clone(obj) { var copy; if (null === obj || 'object' !== typeof obj) { return obj; } copy = obj.constructor(); for (var attr in obj) { if (obj.hasOwnProperty(attr)) { copy[attr] = obj[attr]; } } return copy; } // Load cache var cache = _loadCache(); $.fn.autocompleter = function (method) { if (publics[method]) { return publics[method].apply(this, Array.prototype.slice.call(arguments, 1)); } else if (typeof method === 'object' || !method) { return _init.apply(this, arguments); } return this; }; $.autocompleter = function (method) { if (method === 'defaults') { publics.defaults.apply(this, Array.prototype.slice.call(arguments, 1)); } else if (method === 'clearCache') { publics.clearCache.apply(this, null); } }; })(jQuery, window); </script> <script type="text/javascript"> /** * Crayola colors in JSON format * from: https://gist.github.com/jjdelc/1868136 */ var colors = [ { "hex": "#EFDECD", "label": "Almond", "rgb": "(239, 222, 205)" }, { "hex": "#CD9575", "label": "Antique Brass", "rgb": "(205, 149, 117)" }, { "hex": "#FDD9B5", "label": "Apricot", "rgb": "(253, 217, 181)" }, { "hex": "#78DBE2", "label": "Aquamarine", "rgb": "(120, 219, 226)" }, { "hex": "#87A96B", "label": "Asparagus", "rgb": "(135, 169, 107)" }, { "hex": "#FFA474", "label": "Atomic Tangerine", "rgb": "(255, 164, 116)" }, { "hex": "#FAE7B5", "label": "Banana Mania", "rgb": "(250, 231, 181)" }, { "hex": "#9F8170", "label": "Beaver", "rgb": "(159, 129, 112)" }, { "hex": "#FD7C6E", "label": "Bittersweet", "rgb": "(253, 124, 110)" }, { "hex": "#000000", "label": "Black", "rgb": "(0,0,0)" }, { "hex": "#ACE5EE", "label": "Blizzard Blue", "rgb": "(172, 229, 238)" }, { "hex": "#1F75FE", "label": "Blue", "rgb": "(31, 117, 254)" }, { "hex": "#A2A2D0", "label": "Blue Bell", "rgb": "(162, 162, 208)" }, { "hex": "#6699CC", "label": "Blue Gray", "rgb": "(102, 153, 204)" }, { "hex": "#0D98BA", "label": "Blue Green", "rgb": "(13, 152, 186)" }, { "hex": "#7366BD", "label": "Blue Violet", "rgb": "(115, 102, 189)" }, { "hex": "#DE5D83", "label": "Blush", "rgb": "(222, 93, 131)" }, { "hex": "#CB4154", "label": "Brick Red", "rgb": "(203, 65, 84)" }, { "hex": "#B4674D", "label": "Brown", "rgb": "(180, 103, 77)" }, { "hex": "#FF7F49", "label": "Burnt Orange", "rgb": "(255, 127, 73)" }, { "hex": "#EA7E5D", "label": "Burnt Sienna", "rgb": "(234, 126, 93)" }, { "hex": "#B0B7C6", "label": "Cadet Blue", "rgb": "(176, 183, 198)" }, { "hex": "#FFFF99", "label": "Canary", "rgb": "(255, 255, 153)" }, { "hex": "#1CD3A2", "label": "Caribbean Green", "rgb": "(28, 211, 162)" }, { "hex": "#FFAACC", "label": "Carnation Pink", "rgb": "(255, 170, 204)" }, { "hex": "#DD4492", "label": "Cerise", "rgb": "(221, 68, 146)" }, { "hex": "#1DACD6", "label": "Cerulean", "rgb": "(29, 172, 214)" }, { "hex": "#BC5D58", "label": "Chestnut", "rgb": "(188, 93, 88)" }, { "hex": "#DD9475", "label": "Copper", "rgb": "(221, 148, 117)" }, { "hex": "#9ACEEB", "label": "Cornflower", "rgb": "(154, 206, 235)" }, { "hex": "#FFBCD9", "label": "Cotton Candy", "rgb": "(255, 188, 217)" }, { "hex": "#FDDB6D", "label": "Dandelion", "rgb": "(253, 219, 109)" }, { "hex": "#2B6CC4", "label": "Denim", "rgb": "(43, 108, 196)" }, { "hex": "#EFCDB8", "label": "Desert Sand", "rgb": "(239, 205, 184)" }, { "hex": "#6E5160", "label": "Eggplant", "rgb": "(110, 81, 96)" }, { "hex": "#CEFF1D", "label": "Electric Lime", "rgb": "(206, 255, 29)" }, { "hex": "#71BC78", "label": "Fern", "rgb": "(113, 188, 120)" }, { "hex": "#6DAE81", "label": "Forest Green", "rgb": "(109, 174, 129)" }, { "hex": "#C364C5", "label": "Fuchsia", "rgb": "(195, 100, 197)" }, { "hex": "#CC6666", "label": "Fuzzy Wuzzy", "rgb": "(204, 102, 102)" }, { "hex": "#E7C697", "label": "Gold", "rgb": "(231, 198, 151)" }, { "hex": "#FCD975", "label": "Goldenrod", "rgb": "(252, 217, 117)" }, { "hex": "#A8E4A0", "label": "Granny Smith Apple", "rgb": "(168, 228, 160)" }, { "hex": "#95918C", "label": "Gray", "rgb": "(149, 145, 140)" }, { "hex": "#1CAC78", "label": "Green", "rgb": "(28, 172, 120)" }, { "hex": "#1164B4", "label": "Green Blue", "rgb": "(17, 100, 180)" }, { "hex": "#F0E891", "label": "Green Yellow", "rgb": "(240, 232, 145)" }, { "hex": "#FF1DCE", "label": "Hot Magenta", "rgb": "(255, 29, 206)" }, { "hex": "#B2EC5D", "label": "Inchworm", "rgb": "(178, 236, 93)" }, { "hex": "#5D76CB", "label": "Indigo", "rgb": "(93, 118, 203)" }, { "hex": "#CA3767", "label": "Jazzberry Jam", "rgb": "(202, 55, 103)" }, { "hex": "#3BB08F", "label": "Jungle Green", "rgb": "(59, 176, 143)" }, { "hex": "#FEFE22", "label": "Laser Lemon", "rgb": "(254, 254, 34)" }, { "hex": "#FCB4D5", "label": "Lavender", "rgb": "(252, 180, 213)" }, { "hex": "#FFF44F", "label": "Lemon Yellow", "rgb": "(255, 244, 79)" }, { "hex": "#FFBD88", "label": "Macaroni and Cheese", "rgb": "(255, 189, 136)" }, { "hex": "#F664AF", "label": "Magenta", "rgb": "(246, 100, 175)" }, { "hex": "#AAF0D1", "label": "Magic Mint", "rgb": "(170, 240, 209)" }, { "hex": "#CD4A4C", "label": "Mahogany", "rgb": "(205, 74, 76)" }, { "hex": "#EDD19C", "label": "Maize", "rgb": "(237, 209, 156)" }, { "hex": "#979AAA", "label": "Manatee", "rgb": "(151, 154, 170)" }, { "hex": "#FF8243", "label": "Mango Tango", "rgb": "(255, 130, 67)" }, { "hex": "#C8385A", "label": "Maroon", "rgb": "(200, 56, 90)" }, { "hex": "#EF98AA", "label": "Mauvelous", "rgb": "(239, 152, 170)" }, { "hex": "#FDBCB4", "label": "Melon", "rgb": "(253, 188, 180)" }, { "hex": "#1A4876", "label": "Midnight Blue", "rgb": "(26, 72, 118)" }, { "hex": "#30BA8F", "label": "Mountain Meadow", "rgb": "(48, 186, 143)" }, { "hex": "#C54B8C", "label": "Mulberry", "rgb": "(197, 75, 140)" }, { "hex": "#1974D2", "label": "Navy Blue", "rgb": "(25, 116, 210)" }, { "hex": "#FFA343", "label": "Neon Carrot", "rgb": "(255, 163, 67)" }, { "hex": "#BAB86C", "label": "Olive Green", "rgb": "(186, 184, 108)" }, { "hex": "#FF7538", "label": "Orange", "rgb": "(255, 117, 56)" }, { "hex": "#FF2B2B", "label": "Orange Red", "rgb": "(255, 43, 43)" }, { "hex": "#F8D568", "label": "Orange Yellow", "rgb": "(248, 213, 104)" }, { "hex": "#E6A8D7", "label": "Orchid", "rgb": "(230, 168, 215)" }, { "hex": "#414A4C", "label": "Outer Space", "rgb": "(65, 74, 76)" }, { "hex": "#FF6E4A", "label": "Outrageous Orange", "rgb": "(255, 110, 74)" }, { "hex": "#1CA9C9", "label": "Pacific Blue", "rgb": "(28, 169, 201)" }, { "hex": "#FFCFAB", "label": "Peach", "rgb": "(255, 207, 171)" }, { "hex": "#C5D0E6", "label": "Periwinkle", "rgb": "(197, 208, 230)" }, { "hex": "#FDDDE6", "label": "Piggy Pink", "rgb": "(253, 221, 230)" }, { "hex": "#158078", "label": "Pine Green", "rgb": "(21, 128, 120)" }, { "hex": "#FC74FD", "label": "Pink Flamingo", "rgb": "(252, 116, 253)" }, { "hex": "#F78FA7", "label": "Pink Sherbet", "rgb": "(247, 143, 167)" }, { "hex": "#8E4585", "label": "Plum", "rgb": "(142, 69, 133)" }, { "hex": "#7442C8", "label": "Purple Heart", "rgb": "(116, 66, 200)" }, { "hex": "#9D81BA", "label": "Purple Mountain's Majesty", "rgb": "(157, 129, 186)" }, { "hex": "#FE4EDA", "label": "Purple Pizzazz", "rgb": "(254, 78, 218)" }, { "hex": "#FF496C", "label": "Radical Red", "rgb": "(255, 73, 108)" }, { "hex": "#D68A59", "label": "Raw Sienna", "rgb": "(214, 138, 89)" }, { "hex": "#714B23", "label": "Raw Umber", "rgb": "(113, 75, 35)" }, { "hex": "#FF48D0", "label": "Razzle Dazzle Rose", "rgb": "(255, 72, 208)" }, { "hex": "#E3256B", "label": "Razzmatazz", "rgb": "(227, 37, 107)" }, { "hex": "#EE204D", "label": "Red", "rgb": "(238,32 ,77 )" }, { "hex": "#FF5349", "label": "Red Orange", "rgb": "(255, 83, 73)" }, { "hex": "#C0448F", "label": "Red Violet", "rgb": "(192, 68, 143)" }, { "hex": "#1FCECB", "label": "Robin's Egg Blue", "rgb": "(31, 206, 203)" }, { "hex": "#7851A9", "label": "Royal Purple", "rgb": "(120, 81, 169)" }, { "hex": "#FF9BAA", "label": "Salmon", "rgb": "(255, 155, 170)" }, { "hex": "#FC2847", "label": "Scarlet", "rgb": "(252, 40, 71)" }, { "hex": "#76FF7A", "label": "Screamin' Green", "rgb": "(118, 255, 122)" }, { "hex": "#9FE2BF", "label": "Sea Green", "rgb": "(159, 226, 191)" }, { "hex": "#A5694F", "label": "Sepia", "rgb": "(165, 105, 79)" }, { "hex": "#8A795D", "label": "Shadow", "rgb": "(138, 121, 93)" }, { "hex": "#45CEA2", "label": "Shamrock", "rgb": "(69, 206, 162)" }, { "hex": "#FB7EFD", "label": "Shocking Pink", "rgb": "(251, 126, 253)" }, { "hex": "#CDC5C2", "label": "Silver", "rgb": "(205, 197, 194)" }, { "hex": "#80DAEB", "label": "Sky Blue", "rgb": "(128, 218, 235)" }, { "hex": "#ECEABE", "label": "Spring Green", "rgb": "(236, 234, 190)" }, { "hex": "#FFCF48", "label": "Sunglow", "rgb": "(255, 207, 72)" }, { "hex": "#FD5E53", "label": "Sunset Orange", "rgb": "(253, 94, 83)" }, { "hex": "#FAA76C", "label": "Tan", "rgb": "(250, 167, 108)" }, { "hex": "#18A7B5", "label": "Teal Blue", "rgb": "(24, 167, 181)" }, { "hex": "#EBC7DF", "label": "Thistle", "rgb": "(235, 199, 223)" }, { "hex": "#FC89AC", "label": "Tickle Me Pink", "rgb": "(252, 137, 172)" }, { "hex": "#DBD7D2", "label": "Timberwolf", "rgb": "(219, 215, 210)" }, { "hex": "#17806D", "label": "Tropical Rain Forest", "rgb": "(23, 128, 109)" }, { "hex": "#DEAA88", "label": "Tumbleweed", "rgb": "(222, 170, 136)" }, { "hex": "#77DDE7", "label": "Turquoise Blue", "rgb": "(119, 221, 231)" }, { "hex": "#FFFF66", "label": "Unmellow Yellow", "rgb": "(255, 255, 102)" }, { "hex": "#926EAE", "label": "Violet (Purple)", "rgb": "(146, 110, 174)" }, { "hex": "#324AB2", "label": "Violet Blue", "rgb": "(50, 74, 178)" }, { "hex": "#F75394", "label": "Violet Red", "rgb": "(247, 83, 148)" }, { "hex": "#FFA089", "label": "Vivid Tangerine", "rgb": "(255, 160, 137)" }, { "hex": "#8F509D", "label": "Vivid Violet", "rgb": "(143, 80, 157)" }, { "hex": "#FFFFFF", "label": "White", "rgb": "(255, 255, 255)" }, { "hex": "#A2ADD0", "label": "Wild Blue Yonder", "rgb": "(162, 173, 208)" }, { "hex": "#FF43A4", "label": "Wild Strawberry", "rgb": "(255, 67, 164)" }, { "hex": "#FC6C85", "label": "Wild Watermelon", "rgb": "(252, 108, 133)" }, { "hex": "#CDA4DE", "label": "Wisteria", "rgb": "(205, 164, 222)" }, { "hex": "#FCE883", "label": "Yellow", "rgb": "(252, 232, 131)" }, { "hex": "#C5E384", "label": "Yellow Green", "rgb": "(197, 227, 132)" }, { "hex": "#FFAE42", "label": "Yellow Orange", "rgb": "(255, 174, 66)" } ]; $(function () { $('#nope').autocompleter({ // marker for autocomplete matches highlightMatches: true, // object to local or url to remote search source: colors, // custom template template: '{{ label }} <span>({{ hex }})</span>', // show hint hint: true, // abort source if empty field empty: false, // max results limit: 5, callback: function (value, index, selected) { if (selected) { $('.icon').css('background-color', selected.hex); } } }); }); </script> </html> 提示:你可以先修改部分代码再运行。 转载请注明:有爱前端 » jquery autocomplete类似百度搜索框自动提示插件 喜欢 (0)or分享 (0)