如何使用contenteditable set在div中的每个单词周围放置span标签

时间:2014-09-19 23:42:40

标签: javascript html css contenteditable

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

<div contentEditable id="InputOne" onkeyup="UpdateTextarea(event)"></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= [];
    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>

但我遇到的问题是 1.它不应该每次都重写,因为这是资源密集型的,并且可能导致滞后。 2.因为.innerhtml正在替换光标向后移动的内容,因此当您键入时,文本会反向出现。 所以我想我真正想要的是一种在div中用id InputOne查找空格的方法,并将id设置为序号的关闭和打开span标签。如果你想知道我为什么需要它,那么单词可以是唯一可识别的,这样我就可以逐字设置字体大小。
注意:我宁愿不使用jquery

1 个答案:

答案 0 :(得分:1)

以下似乎对我有用

修改

我添加的函数setCaretLast()不是我的。我发现它Here。我会尽快更新答案以使用正则表达式,这样它就不必一直改变内容。

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>