从内容可编辑div中选择特定文本

时间:2018-04-12 14:31:03

标签: javascript css html5 css3

考虑以下内容可编辑div

.editable-div div {
display: inline-block;
}
<div contenteditable="true" class="editable-div">
  <div> This </div> <div> is a an example</div><div> for inline block</div> <div>elemenst </div> 
</div>

  1. 将鼠标光标放在内容中的任意位置
  2. 按shift + home
  3. 它只会选择内联块div内容
  4. 我想选择整个内容直到div的开头
  5. 我无法更改内部div的内联块样式
  6. 由于上述原因(5)我正在为shift + home和shift + end做一个自定义实现,这就是我需要从div中选择特定文本的原因
  7. *选择为浏览器的文本选择(用户选择),我已经有用于选择div Selecting text in an element (akin to highlighting with your mouse)的整个内容的链接

    但在这里我只想选择特定的文字。请帮忙

1 个答案:

答案 0 :(得分:0)

我认为window.getSelection()正是您所寻找的。

var selection = "";

function getText() {
  if (window.getSelection) {
    selection = window.getSelection().toString();
  } else if (document.selection && document.selection.type !== "Control") {
    selection = document.selection.createRange().text;
  }
  return text;
}