如何将div标签放在div中的每个单词周围用contenteditable集合 [英] How to place span tags around each word in div with contenteditable set

查看:101
本文介绍了如何将div标签放在div中的每个单词周围用contenteditable集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我目前的困境是,我无法在内容可编辑div中的每个单词周围放置html < span> 标签。使用具有顺序div id的span标签。
我的HTML代码如下。

 < div contentEditable id =InputOneonkeyup =UpdateTextarea事件)>< / DIV> 

这里是JavaScript

 < script type =text / javascript> 
var Alert;
var A = 0;
var B = 0;
var C = 0;
var Alert;
var Text2 = [];
var OldStorage = [];
var OutputText = [];
函数UpdateTextarea(e)
{
Alert = document.getElementById('InputOne');
Alert = Alert.innerText || Alert.textContent;
// Alert = Alert.split(\\\
\\\
)。join(< br>);
TextTest = Alert.split(\\\
\\\
);
Text1 = Alert.split(\\\
\\\
);
B = 0;
C = 0;
for(index = 0; index< Text1.length; ++ index){
Text1 [index] =< p>+ Text1 [index] +< / p> ;
/ * if(C === 0){
Text1 [index] =< p>+ Text1 [index];
C = 1;
} else {Text1 [index] = Text1 [index] +< / p>; C = 0;} * /

B ++;
}
Text1 = Text1.join();
// Text1 =< p>+ Text1 +< / p>;
Text2 = Text1.split();

A = 0; (index = 0; index< Text2.length; ++ index){
if(Text2 [index]!==< p>&& Text2 [index]!
! ==< / p>)
{
// alert(Text2 [index]);
OutputText [index] =< span id ='Word - + A +'>+ Text2 [index] +< / span>;
if(Text2 [index]!== OldStorage [index])
{

// Getjson dont bother
var getJSON = function(url,successHandler){
var xhr = typeof XMLHttpRequest!='undefined'
? new XMLHttpRequest()
:new ActiveXObject('Microsoft.XMLHTTP');
xhr.open('get',url,true);
xhr.onreadystatechange = function(){
var data;
if(xhr.readyState == 4){//`完成`

data = JSON.parse(xhr.responseText);
successHandler&& successHandler(数据);

}
};
xhr.send();
};
// end
getJSON(// codeonthecloud.com/School/Science-Fair/Backend.php?Q=\"+Text2[index]+\"&Id=\"+index,function(数据){
document.getElementById(TESTDIV)。innerHTML =< a href ='+ Data.A1 +'>+ Data.A2 +< / a>;

});

OldStorage [index] = Text2 [index];
}
} else {OutputText [index] = Text2 [index];}
A ++;
}
DivA = OutputText.join();
document.getElementById(InputOne)。innerHTML = DivA;

}


< / script>

但是我对JavaScript的问题是
1.它不应该重写每一个因为这是资源密集型的,会造成滞后。
2.因为.innerhtml正在替换光标向后移动的内容,所以当您键入文本时会反向显示。
所以我想我真正想要的是一种方法来找到ID为 InputOne 的div中的空格,并将id设置为a的闭合和打开span标签序号。如果你想知道为什么我需要这样的话,那么这些单词可以唯一标识,以便我可以逐字地设置字体大小。

注意:我宁愿不使用jquery p>

解决方案

以下内容似乎适用于我

编辑



我添加的函数setCaretLast()不是我的。我发现它这里。只要我可以,我会再次更新答案,使用正则表达式,以便它不必一直改变内容。

  var something = document.getElementById('something'); //获取div,我不记得你叫什么了.something.addEventListener('keydown',function(event){if(event.keyCode == 32){event.target.innerHTML = wrap_words(this.innerText ); setCaretLast(this.id); console.log(this.innerHTML);}}); //添加按键事件以收集按键。我让它在用户输入后运行// wrap_words函数。你应该可以设置它//你喜欢。也许只是有这个函数调用(减去event.keycode的东西),而不是blur?function wrap_words(text){var split_text = text.split(''); //通过字符串分割文本var _out = []; //输出数组count = split_text.length; //获取计数。我本来是想用它来做其他的事情,但是被追踪了。对于(var i = 0; i  

< div id = 某些东西contenteditable>你可以在这里输入< / div>


So my current predicament is that I can not place html <span> tags around each word in the content editable div. With the span tags having a sequential div id. The html code I have is below.

<div contentEditable id="InputOne" onkeyup="UpdateTextarea(event)"></div>

and here is the JavaScript

<script type="text/javascript">
    var Alert;
var A=0;
var B=0;
var C=0;
var Alert;
var Text2= [];
var OldStorage= [];
var OutputText= [];
    function UpdateTextarea(e)
    {
Alert = document.getElementById('InputOne');
Alert = Alert.innerText || Alert.textContent;
 //Alert = Alert.split("\n\n").join("<br>");
TextTest=Alert.split("\n\n");
Text1=Alert.split("\n\n");
B=0;
C=0;
for (index = 0; index < Text1.length; ++index) {
Text1[index]="<p> "+Text1[index]+" </p> ";
/*if(C===0){
Text1[index]="<p>"+Text1[index];
C=1;
}else{Text1[index]=Text1[index]+"</p>";C=0;}*/

B++;
}
Text1=Text1.join("");
//Text1="<p>"+Text1+"</p>";
Text2 = Text1.split(" ");

A=0;
for (index = 0; index < Text2.length; ++index) {
if(Text2[index] !== "<p>" && Text2[index] !== "</p>")
    {
    //alert(Text2[index]);
   OutputText[index]="<span id='Word-"+A+"'>"+Text2[index]+" </span>";
    if(Text2[index] !== OldStorage[index])
    {

//Getjson dont bother
var getJSON = function(url, successHandler) {
  var xhr = typeof XMLHttpRequest != 'undefined'
    ? new XMLHttpRequest()
    : new ActiveXObject('Microsoft.XMLHTTP');
  xhr.open('get', url, true);
  xhr.onreadystatechange = function() {
    var data;
    if (xhr.readyState == 4) { // `DONE`

        data = JSON.parse(xhr.responseText);
        successHandler && successHandler(data);

    }
  };
  xhr.send();
};
//end
getJSON("//codeonthecloud.com/School/Science-Fair/Backend.php?Q="+Text2[index]+"&Id="+index, function(Data) {
  document.getElementById("TESTDIV").innerHTML = "<a href='" + Data.A1 + "'>" + Data.A2 + "</a>";

});

        OldStorage[index]=Text2[index];
    }
}else{OutputText[index]=Text2[index];}
A++;
}
DivA=OutputText.join("");
document.getElementById("InputOne").innerHTML=DivA;

    }


</script>

But the problem I have having with the JavaScript is 1. it should not rewrite every time because that is resource intensive and can cause lag. 2. Because .innerhtml is replacing the content the cursor is moving backwards so when you type the text comes out in reverse. So I guess what I really want is a way to find spaces in the div with the id InputOne and place closing and opening span tags with the id set to a sequential number. If you are wondering why I need this it is so that the words can be uniquely identifiable so that I can set font sizes on a word by word basis.
NOTE: I would prefer to not use jquery

解决方案

Following seems to work for me

EDIT

The function that I added in, the setCaretLast(), is not mine. I found it Here. As soon as I can, I'll update the answer again to use regex so that it doesn't have to change the contents ALL the time.

var something = document.getElementById('something'); // Gets the div, I couldn't remember what yours was called.
something.addEventListener('keydown',function(event){
   if(event.keyCode==32) {
    
     event.target.innerHTML = wrap_words(this.innerText);
     setCaretLast(this.id);
     console.log(this.innerHTML);
    }
   
  }); //Adds a key down event to gather the key presses. I have it set to run the 
//wrap_words function after the user hits enter. You should be able to set it however 
//you like. Perhaps just have this function called (minus the event.keycode stuff) on blur instead?

function wrap_words(text){
  var split_text = text.split(' '); //Splits the text by string
  var _out = []; //The output array
  count = split_text.length; //Gets the count. I was originally going to use this for somethign else but got side tracked. 
  for(var i=0;i < count; i++){
      _out[i] = "<span id=\"word-"+i+"\">"+split_text[i]+"</span>"; //I would normally say "use element nodes" but this was just way, way faster.
    }
  
  return _out.join(' '); //Combines the _out array by spaces.
}


//Not my function.
function setCaretLast(el) {
    var el = document.getElementById(el);
    var range = document.createRange();
    var sel = window.getSelection();
    range.setStart(el.childNodes[el.childNodes.length-1], 1);
    range.collapse(true);
    sel.removeAllRanges();
    sel.addRange(range);
    el.focus();
}

<div id="something" contenteditable>
   you can type here
  </div>

这篇关于如何将div标签放在div中的每个单词周围用contenteditable集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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