首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何获得在可内容环境中单击的行?

如何获得在可内容环境中单击的行?
EN

Stack Overflow用户
提问于 2021-02-27 07:55:34
回答 1查看 46关注 0票数 0

我对HTML/JS很陌生,我正在尝试将文本编辑器作为一个小项目。如果我没有清楚地解释我的想法,请原谅我。

假设我的contenteditable div环境中有以下文本,并让|表示光标(就像在大多数编辑器中看到的那样):

代码语言:javascript
运行
复制
hi this is some text
here is some mor|e text
hello, world!

我如何才能返回“这是一些更多的文本”的文本?

我正在使用jQuery,我想要使用onClick处理程序,但这并不响应用于导航的箭头键。我需要什么样的事件处理程序?到目前为止,我已经分析了替换div分隔符的文本,但是我有点不知道如何继续下去。你建议做什么?(一般链接/建议也有效,我正试图通过这个项目学到更多)

编辑,这是我的html:

代码语言:javascript
运行
复制
<div id="editor" class="editor" contenteditable="true"></div>

这是JS:

代码语言:javascript
运行
复制
$(document).on('keydown', '.editor', function(e){
    //detect 'tab' key
    if(e.keyCode == 9){
        //add tab
        document.execCommand('insertHTML', false, '&#009');
        //prevent focusing on next element
        e.preventDefault()
    }
    var text = $("#editor").html();

    console.log("MYLITERAL:" + text);
    // parse the string :)
    // for the div tags, replacing them with \n
    var tmp = text.replace(/<div>/g, "");
    tmp = tmp.replace(/<\/div>/g, "");
    tmp = tmp.replace(/<br>/g, "\n");
    console.log(tmp);
    document.getElementById("demo").innerHTML = tmp;
});
代码语言:javascript
运行
复制
EN

回答 1

Stack Overflow用户

发布于 2021-02-28 01:43:51

您可以尝试以下方法:

代码语言:javascript
运行
复制
var strO, endO, lstEle;

function selectRange(start, end, this_){
    var el = this_,sPos = start,ePos = end;
    var charIndex = 0, range = document.createRange();
    range.setStart(el, 0);
    range.collapse(true);
    var nodeStack = [el], node, foundStart = false, stop = false;
    while (!stop && (node = nodeStack.pop())) {
        if (node.nodeType == 3) {
            var nextCharIndex = charIndex + node.length;
            if (!foundStart && sPos >= charIndex && sPos <= nextCharIndex) {
                range.setStart(node, sPos - charIndex);
                foundStart = true;
            }
            if (foundStart && ePos >= charIndex && ePos <= nextCharIndex) {
                range.setEnd(node, ePos - charIndex);
                stop = true;
            }
            charIndex = nextCharIndex;
        } else {
            var i = node.childNodes.length;
            while (i--) {
                nodeStack.push(node.childNodes[i]);
            }
        }
    }
    var s = (window.getSelection) ? window.getSelection() : document.selection;
    if(window.getSelection) {
        s.removeAllRanges();
        s.addRange(range);
    } else {
        range.select();
    }
}

// node_walk: walk the element tree, stop when func(node) returns false
function node_walk(node, func) {
  var result = func(node);
  for(node = node.firstChild; result !== false && node; node = node.nextSibling){
    result = node_walk(node, func);
    lstEle = node;
  }
  return result;
};

// getCaretPosition: return [start, end] as offsets to elem.textContent that
//   correspond to the selected portion of text
//   (if start == end, caret is at given position and no text is selected)
function getCaretPosition(elem) {
    
    strO = 0, endO = 0, lstEle = elem;
    
  var sel = window.getSelection();
  var cum_length = [0, 0];

  if(sel.anchorNode == elem)
    cum_length = [sel.anchorOffset, sel.extentOffset];
  else {
    var nodes_to_find = [sel.anchorNode, sel.extentNode];
    if(!elem.contains(sel.anchorNode) || !elem.contains(sel.extentNode))
      return undefined;
    else {
      var found = [0,0];
      var i;
      node_walk(elem, function(node) {
        for(i = 0; i < 2; i++) {
          if(node == nodes_to_find[i]) {
            found[i] = true;
            if(found[i == 0 ? 1 : 0])
              return false; // all done
          }
        }

        if(node.textContent && !node.firstChild) {
          for(i = 0; i < 2; i++) {
            if(!found[i])
              cum_length[i] += node.textContent.length;
          }
        }
      });
      strO = cum_length[0];
      endO = strO + lstEle.textContent.length;
      cum_length[0] += sel.anchorOffset;
      cum_length[1] += sel.extentOffset;
    }
  }
  if(cum_length[0] <= cum_length[1])
    return cum_length;
  return [cum_length[1], cum_length[0]];
}

var update = function() {
    $('#test').html(getCaretPosition(this)+' '+strO+' '+endO);
    selectRange(strO, endO, this);
    $('#test').append('<br>'+window.getSelection().toString());
};
$('#editor').on("mouseup keydown keyup", update);
代码语言:javascript
运行
复制
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<div id="editor" class="editor" contenteditable="true">hi this is some text<br>here is some more text<br>hello, world!</div>
<div id="test">test</div>

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66396725

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档