如何在Facebook状态更新框(textarea)中突出显示朋友姓名?

问题描述 投票:7回答:3

在Facebook状态更新框中,当我输入@并开始输入并从fb建议的朋友列表中选择一个名称,比如Steven Gerrard,我的朋友的名字在textarea中突出显示,就像这样

我用Firebug检查过,只有

  • 包含一些格式化文本的div.highlighter(Steven Gerrard在b标签内)
  • div.ui Typeahead中的textarea。我找不到任何有趣的东西
  • 和一个隐藏的输入,其中包含将要发布的实际文本:@ [100001915747xxx:Steven Gerrard]很棒

这背后的秘诀是什么?像ckeditor这样的普通富文本编辑器通常有一个用于显示文本的iframe和一个用于保留原始内容的实际textarea。但在这种情况下,我什么都看不到。有人请点灯吗?

我想做这样的事情,但不知道从哪里开始。另外,如果我想在朋友的名字旁边显示一个小拇指,是否可以呢?

facebook textarea rich-text-editor
3个回答
17
投票

下面是它的工作原理:

  • 您将textarea(在前面)和div(后面)叠加在一起,它们具有相同的大小和相同的字体大小。
  • textarea必须具有透明背景,因此我们可以看到它的文本,但也可以看到它背后的div。
  • 它背后的div将有一个白色文本和白色背景,因此它包含的文本将是透明的。
  • 你在textarea的keyup上设置了一个钩子,然后你把它包含的文本处理为HTML:用以替换换行符,用&nbsp;&nbsp;替换双倍空格,并替换你想要突出显示的所有单词由<span style =“background-color:#D8DFEA;”> </ span>包围的版本。
  • 由于您可以看到textarea后面的高亮div,并且高亮div包含的文本与textarea中的文本完全对齐,并且<span>是可见的,您将会产生幻觉,即textarea中的文本是突出显示。

我已经编写了一个基于jquery的快速示例,因此您可以自己尝试,无需太多代码进行分析。


下面是一个示例代码,您只需复制 - 粘贴 - 保存并尝试:

此示例代码将突出显示一组已定义的单词,此处为:“hello”和“world”。

我会让你以你想要的方式适应它。

<html>
    <head>
        <title></title>
        <!-- Load jQuery -->
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
        <!-- The javascript xontaining the plugin and the code to init the plugin -->
        <script type="text/javascript">
            $(function() {
                // let's init the plugin, that we called "highlight".
                // We will highlight the words "hello" and "world", 
                // and set the input area to a widht and height of 500 and 250 respectively.
                $("#container").highlight({
                    words:  ["hello","world"],
                    width:  500,
                    height: 250
                });
            });

            // the plugin that would do the trick
            (function($){
                $.fn.extend({
                    highlight: function() {
                        // the main class
                        var pluginClass = function() {};
                        // init the class
                        // Bootloader
                        pluginClass.prototype.__init = function (element) {
                            try {
                                this.element = element;
                            } catch (err) {
                                this.error(err);
                            }
                        };
                        // centralized error handler
                        pluginClass.prototype.error = function (e) {
                            // manage error and exceptions here
                            //console.info("error!",e);
                        };
                        // Centralized routing function
                        pluginClass.prototype.execute = function (fn, options) {
                            try {
                                options = $.extend({},options);
                                if (typeof(this[fn]) == "function") {
                                    var output = this[fn].apply(this, [options]);
                                } else {
                                    this.error("undefined_function");
                                }
                            } catch (err) {
                                this.error(err);
                            }
                        };
                        // **********************
                        // Plugin Class starts here
                        // **********************
                        // init the component
                        pluginClass.prototype.init = function (options) {
                            try {
                                // the element's reference ( $("#container") ) is stored into "this.element"
                                var scope                   = this;
                                this.options                = options;

                                // just find the different elements we'll need
                                this.highlighterContainer   = this.element.find('#highlighterContainer');
                                this.inputContainer         = this.element.find('#inputContainer');
                                this.textarea               = this.inputContainer.find('textarea');
                                this.highlighter            = this.highlighterContainer.find('#highlighter');

                                // apply the css
                                this.element.css('position','relative');

                                // place both the highlight container and the textarea container
                                // on the same coordonate to superpose them.
                                this.highlighterContainer.css({
                                    'position':         'absolute',
                                    'left':             '0',
                                    'top':              '0',
                                    'border':           '1px dashed #ff0000',
                                    'width':            this.options.width,
                                    'height':           this.options.height,
                                    'cursor':           'text'
                                });
                                this.inputContainer.css({
                                    'position':         'absolute',
                                    'left':             '0',
                                    'top':              '0',
                                    'border':           '1px solid #000000'
                                });
                                // now let's make sure the highlit div and the textarea will superpose,
                                // by applying the same font size and stuffs.
                                // the highlighter must have a white text so it will be invisible
                                this.highlighter.css({

                                    'padding':          '7px',
                                    'color':            '#eeeeee',
                                    'background-color': '#ffffff',
                                    'margin':           '0px',
                                    'font-size':        '11px',
                                    'font-family':      '"lucida grande",tahoma,verdana,arial,sans-serif'
                                });
                                // the textarea must have a transparent background so we can see the highlight div behind it
                                this.textarea.css({
                                    'background-color': 'transparent',
                                    'padding':          '5px',
                                    'margin':           '0px',
                                    'font-size':        '11px',
                                    'width':            this.options.width,
                                    'height':           this.options.height,
                                    'font-family':      '"lucida grande",tahoma,verdana,arial,sans-serif'
                                });

                                // apply the hooks
                                this.highlighterContainer.bind('click', function() {
                                    scope.textarea.focus();
                                });
                                this.textarea.bind('keyup', function() {
                                    // when we type in the textarea, 
                                    // we want the text to be processed and re-injected into the div behind it.
                                    scope.applyText($(this).val());
                                });
                            } catch (err) {
                                this.error(err);
                            }
                            return true;
                        };
                        pluginClass.prototype.applyText = function (text) {
                            try {
                                var scope                   = this;

                                // parse the text:
                                // replace all the line braks by <br/>, and all the double spaces by the html version &nbsp;
                                text = this.replaceAll(text,'\n','<br/>');
                                text = this.replaceAll(text,'  ','&nbsp;&nbsp;');

                                // replace the words by a highlighted version of the words
                                for (var i=0;i<this.options.words.length;i++) {
                                    text = this.replaceAll(text,this.options.words[i],'<span style="background-color: #D8DFEA;">'+this.options.words[i]+'</span>');
                                }

                                // re-inject the processed text into the div
                                this.highlighter.html(text);

                            } catch (err) {
                                this.error(err);
                            }
                            return true;
                        };
                        // "replace all" function
                        pluginClass.prototype.replaceAll = function(txt, replace, with_this) {
                            return txt.replace(new RegExp(replace, 'g'),with_this);
                        }

                        // don't worry about this part, it's just the required code for the plugin to hadle the methods and stuffs. Not relevant here.
                        //**********************
                        // process
                        var fn;
                        var options;
                        if (arguments.length == 0) {
                            fn = "init";
                            options = {};
                        } else if (arguments.length == 1 && typeof(arguments[0]) == 'object') {
                            fn = "init";
                            options = $.extend({},arguments[0]);
                        } else {
                            fn = arguments[0];
                            options = $.extend({},arguments[1]);
                        }

                        $.each(this, function(idx, item) {
                            // if the component is not yet existing, create it.
                            if ($(item).data('highlightPlugin') == null) {
                                $(item).data('highlightPlugin', new pluginClass());
                                $(item).data('highlightPlugin').__init($(item));
                            }
                            $(item).data('highlightPlugin').execute(fn, options);
                        });
                        return this;
                    }
                });

            })(jQuery);


        </script>
    </head>
    <body>

        <div id="container">
            <div id="highlighterContainer">
                <div id="highlighter">

                </div>
            </div>
            <div id="inputContainer">
                <textarea cols="30" rows="10">

                </textarea>
            </div>
        </div>

    </body>
</html>

如果您有任何疑问或需要有关此代码的帮助,请与我们联系。


2
投票

在查看Facebook的方式后,我看到屏幕上显示的文字是:

<span class="highlighterContent"><b>Ws Dev</b> is good</span>

该跨度放在一个表(有很多div容器)中,这是相应的样式。

所以我认为这是一个过程:

  1. 当您在框中键入内容时,Facebook确实有一个文本区域可以捕获您键入的内容,但使用javascript在表格中显示键入的HTML内容。
  2. 提交时,隐藏输入(您已在问题中找到)中的格式化内容将被提交。这就像“@ [100001915747xxx:史蒂文杰拉德]太棒了”。
  3. 格式化消息提交时,它将保存到数据库中。每次加载页面时,都会从保存的消息中编写并返回HTML。

要获得类似的效果,您可以使用任何jQuery autocomplete plugin


1
投票

示例代码使用Julien在http://jsfiddle.net/SBBZm/描述的技术

在示例中突出显示以大写字母开头的单词。

© www.soinside.com 2019 - 2024. All rights reserved.