使用javascript添加行号并在textarea中突出显示文本 [英] Adding line numbers and highlighting text inside textarea using javascript
问题描述
我有一个代码,用于使用javascript在textarea中添加行号,还有一个代码,用于使用jquery突出显示textarea中的文本。
添加行号javascript代码 - 有2个div,第1个div在textarea后面,第2个div用于行号。
使用jquery代码突出显示文本 - 有3个div。
我想在textarea.I中结合这两个功能(突出显示文本和添加行号)尝试了很多使用这两个代码,但没有一个工作。我有这些div的问题。我已经粘贴了javascript和jquery代码。任何人都可以帮我看看如何结合这两个功能。
var lineObjOffsetTop = 2 ;
函数createTextAreaWithLines(id)
{
var el = document.createElement(' DIV');
var ta = document.getElementById(id);
ta.parentNode.insertBefore(el,ta);
el.appendChild(ta);
el.className = ' textAreaWithLines';
el.style.width = ' 50%';
ta.style.position = ' 绝对';
ta.style.left = ' 30px';
el.style.height = ' 91%';
el.style.overflow = ' hidden';
el.style。 float = ' left 跨度>;
el.style.position = ' relative';
var lineObj = document.createElement(' DIV'跨度>);
lineObj.style.position = ' 绝对';
lineObj.style.top = lineObjOffsetTop + ' px';
lineObj.style.left = ' 0px';
lineObj.style.width = ' 27px';
el.insertBefore(lineObj,ta);
lineObj.style.textAlign = ' right';
lineObj.className = ' lineObj';
var string = ' ';
for ( var no = 1 ; no< 10000; no ++){
if ( string .length> 0) string = string + ' <峰; br>'跨度>;
string = string + no;
}
ta.onkeydown = function(){positionLineObj(lineObj,ta); };
ta.onmousedown = function(){positionLineObj(lineObj,ta); };
ta.onscroll = function(){positionLineObj(lineObj,ta); };
ta.onblur = function(){positionLineObj(lineObj,ta); };
ta.onfocus = function(){positionLineObj(lineObj,ta); };
ta.onmouseover = function(){positionLineObj(lineObj,ta); };
lineObj.innerHTML = string ;
}
函数positionLineObj(obj,ta)
{
obj.style.top =(ta.scrollTop * -1 + lineObjOffsetTop)+ ' px';
< /脚本>
< style>
。 textAreaWithLines {
font-family : courier;
border : 1px纯灰色;
}
。 textAreaWithLines textarea ,。 textAreaWithLines div {
border : 0px;
line-height : 120% ;
font-size : 12px;
}
。 lineObj {
颜色 : blue;
}
< / 样式 >
// 在textarea内添加行号结束
jquery代码(突出显示文本)< br $> b $ b
script type =text / javascriptsrc =http://ajax.googleapis.com/ AJAX /库/ jquery的/ 1.4 / jquery.min.js>< /脚本>
< script type =text / javascript>
$(function(){
//让我们初始化插件,我们称之为突出显示。
//我们将突出显示单词hello和world,
//并将输入区域分别设置为widht和高度500和250.
$(#container1)。highlight({
words:[[(\\\\\ \)(。+?)(\\}),$ 1 $ 2 $ 3]],
宽度:500,
身高:125,
计数:1
});
});
//这个插件可以解决这个问题
(函数($){
$ .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.options.count);
this.inputContainer = this.element.find('#inputContainer'+ this.options.count);
this.textarea = this.inputContainer.find('#text');
this.highlighter = this.highlighterContainer.find('#highlighter'+ this.options.count);
//应用css
this.element.css({'position':'relative',
'溢出':'auto',
'背景':'无重复滚动0 0 #FFFFFF',
'height':this.options.height + 2,
'width':this.options.width + 19,
'边框':'1px solid'
});
//将高亮容器和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 ',
'z-index':'1'
});
this.inputContainer.css({
'position':'absolute',
'left':'0',
'top':'0',
'border':'0px solid#000000',
'z-index':'2',
'background':'none repeat scroll 0 0 transparent'
});
//现在让我们通过应用相同的字体大小和内容来确保高亮的div和textarea将重叠,
//。
//荧光笔必须有一个白色文本,因此它将是不可见的
var isWebKit = navigator.userAgent.indexOf(WebKit)> -1,
isOpera = navigator.userAgent.indexOf(Opera)> -1,
isIE / * @ cc_on = true @ * /,
isIE6 = isIE&& !window.XMLHttpRequest; //尽管变量名称,这意味着如果IE低于v7
if(isIE || isOpera){
var padding ='6px 5px';
}
else {
var padding ='5px 6px';
}
this.highlighter.css({
'padding':padding,
'color':'#eeeeee',
'background-color':' #ffffff',
'margin':'0px',
'font-size':'11px',
'line-height':'12px',
'字体-family':'lucida grande,tahoma,verdana,arial,sans-serif'
});
// textarea必须具有透明背景,所以我们可以看到它后面的高亮div
this.textarea.css({
'background-color':'transparent' ,
'padding':'5px',
'margin':'0px',
'width':this.options.width,
'height':this.options .height,
'font-size':'11px',
'line-height':'12px',
'font-family':'lucida grande,tahoma,verdana ,arial,sans-serif',
'溢出':'自动',
'边界':'0px solid#000000'
});
//应用钩子
this.highlighterContainer.bind('click',function(){
scope.textarea.focus();
});
this.textarea.bind('keyup',function(){
//当我们输入textarea时,
//我们希望文本被处理并重新注入到它后面的div。
scope.applyText($(this).val());
});
scope.applyText(this.textarea.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;');
text = this.replaceAll(text,'','& nbsp;');
//用高亮的单词
替换单词(var i = 0; i< this.options.words.length; i ++){
text = this.replaceAll(text,this.options.words [i] [0],'< span style =background-color:lightblue;>'+ this.options.words [i] [1] +'< ; /跨度>');
// text = this.replaceAll(text,'(\\ [b])(。+?)(\\ [/ b])','< span style =font-重量:粗体;背景颜色:#D8DFEA;> $ 1 $ 2 $ 3< / span>');
}
//将已处理的文本重新注入div
this.highlighter.html(text);
if(this.highlighter [0] .clientHeight> this.options.height){
// document.getElementById(highlighter0)
this.textarea [0] .style。 height = this.highlighter [0] .clientHeight +19+px;
}
else {
this.textarea [0] .style.height = this.options.height;
}
} 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 = {};
} 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($ (item).data('highlightPlugin')== null){
$(item).data('highlightPlugin',new pluginClass());
$(item).data('highlightPlugin' ).__ init($(item));
}
$(item).data('highlightPlugin')。execute(fn,options);
});
返回此;
}
});
})(jQuery);
< body >
< div < span class =code-attribute> id = container1 >
< div id = highlighterContainer1 >
< div id = highlighter1 > < / div >
< / div >
< div id = inputContainer1 >
< textarea id =' text' 行 = 30 cols = 30 > < / textarea >
< / div >
< / div >
< script > createtext('text')< / script >
(function(){
//让我们初始化插件,我们称之为突出显示。
//我们将突出显示单词hello和world,
//并将输入区域设置为widht和高度分别为500和250.
< blockquote>(#container1)。highlight({
words:[[(\\\\)(。+?)(\\})),
1
I have a code for adding line numbers inside textarea using javascript and also have a code for highlighting text in textarea using jquery.
Adding line numbers javascript code- Has 2 div,1st div is behind textarea and 2nd div is for line numbers.
Highlighting text using jquery code - Has 3 div.
I want to combine these two features(highlighting text and adding line numbers)inside textarea.I tried a lot using these two codes but none of them worked.I had a problem with these div's. I have pasted below javascript and jquery code. Can anybody pls help me to how to combine these two functions.
var lineObjOffsetTop = 2;
function createTextAreaWithLines(id)
{
var el = document.createElement('DIV');
var ta = document.getElementById(id);
ta.parentNode.insertBefore(el,ta);
el.appendChild(ta);
el.className='textAreaWithLines';
el.style.width ='50%';
ta.style.position = 'absolute';
ta.style.left = '30px';
el.style.height = '91%';
el.style.overflow='hidden';
el.style.float='left';
el.style.position = 'relative';
var lineObj = document.createElement('DIV');
lineObj.style.position = 'absolute';
lineObj.style.top = lineObjOffsetTop + 'px';
lineObj.style.left = '0px';
lineObj.style.width = '27px';
el.insertBefore(lineObj,ta);
lineObj.style.textAlign = 'right';
lineObj.className='lineObj';
var string = '';
for(var no=1;no<10000;no++){
if(string.length>0)string = string + '<br>';
string = string + no;
}
ta.onkeydown = function() { positionLineObj(lineObj,ta); };
ta.onmousedown = function() { positionLineObj(lineObj,ta); };
ta.onscroll = function() { positionLineObj(lineObj,ta); };
ta.onblur = function() { positionLineObj(lineObj,ta); };
ta.onfocus = function() { positionLineObj(lineObj,ta); };
ta.onmouseover = function() { positionLineObj(lineObj,ta); };
lineObj.innerHTML = string;
}
function positionLineObj(obj,ta)
{
obj.style.top = (ta.scrollTop * -1 + lineObjOffsetTop) + 'px';
</script>
<style>
.textAreaWithLines{
font-family:courier;
border:1px solid grey;
}
.textAreaWithLines textarea,.textAreaWithLines div{
border:0px;
line-height:120%;
font-size:12px;
}
.lineObj{
color:blue;
}
</style>
//end of adding line numbers inside textarea
jquery code(highlighting text)
script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script> <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. $("#container1").highlight({ words: [["(\\\\)(.+?)(\\})","$1$2$3"]], width: 500, height: 125, count: 1 }); }); // 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.options.count); this.inputContainer = this.element.find('#inputContainer'+this.options.count); this.textarea = this.inputContainer.find('#text'); this.highlighter = this.highlighterContainer.find('#highlighter'+this.options.count); // apply the css this.element.css({'position':'relative', 'overflow':'auto', 'background':'none repeat scroll 0 0 #FFFFFF', 'height':this.options.height+2, 'width':this.options.width+19, 'border':'1px solid' }); // 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', 'z-index': '1' }); this.inputContainer.css({ 'position': 'absolute', 'left': '0', 'top': '0', 'border': '0px solid #000000', 'z-index': '2', 'background': 'none repeat scroll 0 0 transparent' }); // 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 var isWebKit = navigator.userAgent.indexOf("WebKit") > -1, isOpera = navigator.userAgent.indexOf("Opera") > -1, isIE /*@cc_on = true @*/, isIE6 = isIE && !window.XMLHttpRequest; // Despite the variable name, this means if IE lower than v7 if (isIE || isOpera){ var padding = '6px 5px'; } else { var padding = '5px 6px'; } this.highlighter.css({ 'padding': padding, 'color': '#eeeeee', 'background-color': '#ffffff', 'margin': '0px', 'font-size': '11px' , 'line-height': '12px' , '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', 'width': this.options.width, 'height': this.options.height, 'font-size': '11px', 'line-height': '12px' , 'font-family': '"lucida grande",tahoma,verdana,arial,sans-serif', 'overflow': 'auto', 'border': '0px solid #000000' }); // 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()); }); scope.applyText(this.textarea.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 text = this.replaceAll(text,'\n','<br/>'); text = this.replaceAll(text,' ',' '); text = this.replaceAll(text,' ',' '); // 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][0],'<span style="background-color:lightblue;">'+this.options.words[i][1]+'</span>'); //text = this.replaceAll(text,'(\\[b])(.+?)(\\[/b])','<span style="font-weight:bold;background-color: #D8DFEA;">$1$2$3</span>'); } // re-inject the processed text into the div this.highlighter.html(text); if (this.highlighter[0].clientHeight > this.options.height) { // document.getElementById("highlighter0") this.textarea[0].style.height=this.highlighter[0].clientHeight +19+"px"; } else { this.textarea[0].style.height=this.options.height; } } 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);
<body>
<div id="container1">
<div id="highlighterContainer1">
<div id="highlighter1"></div>
</div>
<div id="inputContainer1">
<textarea id='text' rows=30 cols=30 ></textarea>
</div>
</div>
<script>createtext('text')</script>
(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.
("#container1").highlight({ words: [["(\\\\)(.+?)(\\})","
1
这篇关于使用javascript添加行号并在textarea中突出显示文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!