突出显示textarea内的文本 [英] Highlight text inside of a textarea

查看:91
本文介绍了突出显示textarea内的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用javascript突出显示textarea内的文字?更改文本区域的一部分背景或者选择文本的一部分选择

解决方案

试试我今天早上写的这段代码,它会突出显示一组定义的单词:

 < html> 
< head>
< title>< / title>
<! - 加载jQuery - >
< script type =text / javascriptsrc =http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js>< / script>
<! - javascript包含插件和初始化插件的代码 - >
< script type =text / javascript>
$(function(){
//让我们初始化插件,我们称之为突出显示。
//我们将突出显示单词hello和world,
//并将输入区域分别设置为widht和高度500和250.
$(#container)。highlight({
words:[hello,world],
宽度:500,
身高:250
});
});

//这个插件可以解决这个问题
(函数($){
$ .fn.extend({
highlight:function(){
//主类
var pluginClass = function(){};
// init类
// Bootloader
pluginClass.prototype .__ init = function(element) {
try {
this.element = element;
} catch(err){
this.error(err);
}
};
//集中错误处理程序
pluginClass.prototype.error = function(e){
//在这里管理错误和异常
//console.info(\"error!\",e );
};
//集中路由功能
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(错误){
this.error(err);
}
};
// **********************
//插件类从这里开始
// ****** ****************
//初始化组件
pluginClass.prototype.init = function(options){
try {
//元素的引用($(#container))存储在this.element中
var scope = this;
this.options = options;

//找到我们需要的不同元素
this.highlighterContainer = this.element.find('#highlighterContainer');
this.inputContainer = this.element.find('#inputContainer');
this.textarea = this.inputContainer.find('textarea');
this.highlighter = this.highlighterContainer.find('#highlighter');

//应用css
this.element.css('position','relative');

//将高亮容器和textarea容器
//放在同一个coordonate上以叠加它们。
this.highlighterContainer.css({
'position':'absolute',
'left':'0',
'top':'0',
'border':'1px dashed#ff0000',
'width':this.options.width,
'height':this.options.height,
'grsor':'text '
});
this.inputContainer.css({
'position':'absolute',
'left':'0',
'top':'0',
'border':'1px solid#000000'
});
//现在让我们通过应用相同的字体大小和内容来确保高亮的div和textarea将重叠,
//。
//荧光笔必须有白色文字,因此它将是隐形的
this.highlighter.css({

'padding':'7px',
' color':'#eeeeee',
'background-color':'#fffffff',
'margin':'0px',
'font-size':'11px',
'font-family':'lucida grande,tahoma,verdana,arial,sans-serif'
});
// textarea必须具有透明背景,所以我们可以看到它背后的高亮div
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'
});

//应用钩子
this.highlighterContainer.bind('click',function(){
scope.textarea.focus();
});
this.textarea.bind('keyup',function(){
//当我们输入textarea时,
//我们希望文本被处理并重新注入到它后面的div。
scope.applyText($(this).val());
});
} catch(错误){
this.error(err);
}
返回true;
};
pluginClass.prototype.applyText = function(text){
try {
var scope = this;

//解析文本:
//用< br />替换所有行制动器,用html版本替换所有双行空格& nbsp;
text = this.replaceAll(text,'\ n','< br />');
text = this.replaceAll(text,'','& nbsp;& nbsp;');

//用高亮的单词
替换单词(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>' );
}

//将已处理的文本重新注入div
this.highlighter.html(text);

} catch(错误){
this.error(err);
}
返回true;
};
//替换所有函数
pluginClass.prototype.replaceAll = function(txt,replace,with_this){
return txt.replace(new RegExp(replace,'g'),with_this );
}

//不要担心这个部分,它只是插件所需的代码来处理方法和内容。这里不相关。
// **********************
//处理
var fn;
var期权;
if(arguments.length == 0){
fn =init;
options = {};
}否则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($ (item).data('highlightPlugin')== null){
$(item).data('highlightPlugin',new pluginClass());
$(item).data('highlightPlugin' ).__ init($(item));
}
$(item).data('highlightPlugin')。execute(fn,options);
});
返回此;
}
});

})(jQuery);


< / script>
< / head>
< body>

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

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

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

< / body>
< / html>

这是为另一篇文章写的(http://facebook.stackoverflow.com/questions/7497824/如何突出显示朋友的名字在facebook-status-update-box-textarea / 7597420#7597420),但它似乎是你正在寻找的。

Is it possible to highlight text inside of a textarea using javascript? Either changing the background of just a portion of the text area or making a portion of the text selected?

解决方案

Try this piece of code I wrote this morning, it will highlight a defined set of words:

<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>

This was written for another post (http://facebook.stackoverflow.com/questions/7497824/how-to-highlight-friends-name-in-facebook-status-update-box-textarea/7597420#7597420), but it seems to be what you're searching for.

这篇关于突出显示textarea内的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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