在文本中间自动完成(如 Google Plus) [英] autocomplete in middle of text (like Google Plus)

查看:27
本文介绍了在文本中间自动完成(如 Google Plus)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有很多选项可用于自动完成.他们中的大多数似乎都适用于输入的前几个字母.

There are tons of options out there for doing autocompletion. Most of them seem to work on the first few letters that are typed.

在 Google Plus 中,自动完成选项在输入 @ 后很快就会下降,无论它出现在表单字段中的哪个位置,并使用紧跟在 @ 后面的字母来引导自动完成.(也挺好看的!)

In Google Plus, an autocomplete option drops down soon after typing @, no matter where it occurs in the form field, and uses the letters immediately following @ to guide the autocomplete. (It also looks quite nice!)

有没有人共享代码来做这种事情?

Has anybody shared code to do this sort of thing?

有没有人有任何尝试实现这个玩具版本的指针(例如在 jQuery 中)?

Does anybody have any pointers for trying to implement a toy version of this (e.g. in jQuery)?

推荐答案

这可以通过 jQueryUI 的自动完成小部件.具体来说,您可以改编本演示来满足您的需求.举个例子:

This is possible with jQueryUI's autocomplete widget. Specifically, you can adapt this demo to satisfy your requirement. Here's an example:

function split(val) {
    return val.split(/@s*/);
}

function extractLast(term) {
    return split(term).pop();
}

var availableTags = [ ... ]; // Your local data source.

$("#tags")
// don't navigate away from the field on tab when selecting an item
.bind("keydown", function(event) {
    if (event.keyCode === $.ui.keyCode.TAB && $(this).data("autocomplete").menu.active) {
        event.preventDefault();
    }
}).autocomplete({
    minLength: 0,
    source: function(request, response) {
        var term = request.term,
            results = [];
        if (term.indexOf("@") >= 0) {
            term = extractLast(request.term);
            if (term.length > 0) {
                results = $.ui.autocomplete.filter(
                availableTags, term);
            }
        }
        response(results);
    },
    focus: function() {
        // prevent value inserted on focus
        return false;
    },
    select: function(event, ui) {
        var terms = split(this.value);
        // 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.value = terms.join("");
        return false;
    }
});

它在这里工作:http://jsfiddle.net/UdUrk/

如果您需要更多信息(例如如何使其与远程数据源一起使用),请告诉我.

Let me know if you need any more information (such as how to make it work with a remote datasource).

更新:以下是使用远程数据源(StackOverflow 的 API)的示例:http://jsfiddle.net/LHNky/.它还包括自动完成建议的自定义显示.

Update: Here's an example using a remote datasource (StackOverflow's API): http://jsfiddle.net/LHNky/. It also includes custom display of autocomplete suggestions.

这篇关于在文本中间自动完成(如 Google Plus)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆