簡體   English   中英

單擊內容可編輯區域時啟用自動完成下拉菜單

[英]Enable autocomplete dropdown when clicked on the contenteditable area

有一個帶有一些數據的contenteditable span標簽。 當我編輯span標簽內現有的數據時,我需要清除完整數據,然后從自動完成列表中獲得建議。 我需要的是,當用戶單擊span標簽而不編輯任何現有數據時,我想顯示數據。 請幫幫我。 先感謝您。

這是一個基於http://jqueryui.com/autocomplete/#multiple的非常簡單的示例

 $(function() { var availableTags = [ "ActionScript", "AppleScript", "Asp", "BASIC", "C", "C++", "Clojure", "COBOL", "ColdFusion", "Erlang", "Fortran", "Groovy", "Haskell", "Java", "JavaScript", "Lisp", "Perl", "PHP", "Python", "Ruby", "Scala", "Scheme" ]; function split(val) { return val.split(" "); } function extractLast(term) { return split(term).pop(); } function moveCursorToEnd(el) { if (typeof el.selectionStart == "number") { el.selectionStart = el.selectionEnd = el.value.length; } else if (typeof el.createTextRange != "undefined") { el.focus(); var range = el.createTextRange(); range.collapse(false); range.select(); } } $("#content") // don't navigate away from the field on tab when selecting an item .on("keydown", function(event) { if (event.keyCode === $.ui.keyCode.TAB && $(this).autocomplete("instance").menu.active) { event.preventDefault(); } }) .autocomplete({ minLength: 0, source: function(request, response) { // delegate back to autocomplete, but extract the last term response($.ui.autocomplete.filter( availableTags, extractLast(request.term))); }, focus: function() { // prevent value inserted on focus return false; }, select: function(event, ui) { var val = $(this).html(); var terms = split(val); // remove the current input terms.pop(); // add the selected item terms.push(ui.item.value); // add placeholder to get the comma-and-space at the end terms.push(""); $(this).html(terms.join(" ")); moveCursorToEnd($(this)[0]); return false; } }); }); 
 #content { min-width: 1em; min-height: 1em; border: 1px solid #eee; border-radius: 3px; padding-left: 1px; } 
 <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <div class="ui-widget"> <label for="content">Edit content: </label> <span id="content" contenteditable="true">Basic</span> </div> 

如您所見,已對其進行了修改,以使用“”(空格)代替“,”進行拆分和合並。 假設您正在創建句子或單詞列表,則效果很好。

希望能有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM