选择不返回原始位置

时间:2018-04-13 04:19:13

标签: javascript html

问题

所以我尝试按照How to select text range within a contenteditable div that has no child nodes?中的答案进行操作,但在我点击Tab键后,它在新插入的\t之后没有返回到该位置。

期望的行为

E.g | =游标

sen|tence

*press tab*

sen\t|tence

小提琴似乎运行得更好:https://jsfiddle.net/hw4mps0k/4/



function insertTab (event) {
  if (event.which === 9)
  {
			event.preventDefault()
      let td = event.target
      let text = td.innerText
      let selection = window.getSelection()
      let node = td.childNodes[0]
      let start = selection.anchorOffset
      let end = selection.focusOffset
      let remove = end - start

      let new_range = document.createRange()
      new_range.setStart(node, start)
      new_range.setEnd(node, start)
      new_range.collapse(start)

      text = text.split("")
      text.splice(start, remove, "\t")
      text = text.join("")
      td.innerText = text;
      console.log(text)

      selection.removeAllRanges()
      selection.addRange(new_range)
			td.focus()
  }
}

td {
  border: 1px solid black;
  width: 50px;
  height: 50px;
	white-space: pre;
}

body {
 	width:	100vw;
}

<table>
	<tbody>
		<tr>
			<td contenteditable="true" onkeydown="insertTab(event)"></td>
		</tr>		
	</tbody>

</table>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

也许这不是完美的解决方案,但这就是我想出的:

&#13;
&#13;
//<![CDATA[
/* external.js */
var doc, htm, bod, M, I, old = onload; // for use on other loads
onload = function(){
if(old)old(); // change old var name if using technique on other pages
doc = document; htm = doc.documentElement; bod = doc.body; 
M = function(tag){
  return doc.createElement(tag);
}
I = function(id){
  return doc.getElementById(id);
}
I('f').onsubmit = function(e){
  // do all your submission stuff here
  return false;
}
var et = I('edit');
et.onkeydown = function(e){
  var tab = false;
  if(e.key && e.key === 'Tab'){
    tab = true;
  }
  else{
    var k = e.keyCode || e.which;
    if(k === 9)tab = true;
  }
  if(tab){
    this.value = this.value+'\t'; this.focus(); 
    return false;
  }  
}
}// end load
&#13;
/* external.css */
html,body{
  padding:0; margin:0;
}
body{
  background:#000; overflow-y:scroll;
}
.main{
  width:940px; background:#ccc; padding:20px; margin:0 auto;
}
#edit{
  width:50px; height:50px; background:#fff; border:1px solid #000;
}
&#13;
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
  <head>
    <meta http-equiv='content-type' content='text/html;charset=utf-8' />
    <meta name='viewport' content='width=device-width' />
    <title>Test Template</title>
    <link type='text/css' rel='stylesheet' href='external.css' />
    <script type='text/javascript' src='external.js'></script>
  </head>
<body>
  <div class='main'>
    <form id='f'>
      <table>
        <tbody>
          <tr>
            <td><input id='edit' type='text' value='' /></td>
          </tr>
        </tbody> 
      </table>    
    </form>
  </div>
</body>
</html>
&#13;
&#13;
&#13;

现在标签被视为空格。