如果选择了文本,则以跨度换行

时间:2016-10-27 23:15:19

标签: javascript html

当命中退格/删除键时,我使用以下函数用<span>包装突出显示的文本。

&#13;
&#13;
$(document).keydown(function(event) {
  var selection = document.getSelection();
  typoNumber++;
  if (event.keyCode == 8 || event.keyCode == 46) {
    event.preventDefault();
    var span = document.createElement("span");
    span.setAttribute('id', 'typo' + typoNumber);
    span.className = "deleted typo";
    span.setAttribute('contenteditable', 'false');
    if (window.getSelection) {
      var sel = window.getSelection();
      if (sel.rangeCount) {
        var range = sel.getRangeAt(0).cloneRange();
        range.surroundContents(span);
        sel.removeAllRanges();
        sel.addRange(range);
      }
    }
  }
});
&#13;
.deleted.typo {
  background: rgba(100,100,100,0.25);
 }
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div>Here is text to experiment with.</div>
&#13;
&#13;
&#13;

如果选择了文本,我只希望函数运行(这样我就不会得到一堆空的<span>元素)。我尝试将第一个if语句更改为以下内容:

 if (selection !== '' && event.keyCode == 8 || event.keyCode == 46) {

但那并没有奏效。有什么想法吗?

2 个答案:

答案 0 :(得分:1)

将条件更改为此应该可以帮助您:

if(
  selection.anchorOffset !== selection.focusOffset 
  && 
  (event.keyCode == 8 || event.keyCode == 46)
) 

小提琴:https://jsfiddle.net/34L49xLr/

答案 1 :(得分:0)

getSelection实际返回一个对象(SelectionObject) - 您可以将其转换为字符串,然后检查其长度以确定是否选择了任何文本。像这样:

&#13;
&#13;
// Make sure you're initializing this somewhere; this function expects it defined.
var typoNumber = 0;

$(document).keydown(function(event) {
  var selection = document.getSelection();

  // If there's nothing selected, bail out here.
  // If you want to increment typoNumber even with an empty selection,
  // move that line above this block.
  if (selection.toString().length < 1) {
    return;
  }

  typoNumber++;
  if (event.keyCode == 8 || event.keyCode == 46) {
    event.preventDefault();
    var span = document.createElement("span");
    span.setAttribute('id', 'typo' + typoNumber);
    span.className = "deleted typo";
    span.setAttribute('contenteditable', 'false');
    if (window.getSelection) {
      var sel = window.getSelection();
      if (sel.rangeCount) {
        var range = sel.getRangeAt(0).cloneRange();
        range.surroundContents(span);
        sel.removeAllRanges();
        sel.addRange(range);
      }
    }
  }
});
&#13;
/* so we can see where the spans are... */
.deleted.typo {
  display: inline-block;
  padding: 3px;
  background: rgba(100,100,100,0.25);
 }
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div>Here is text to experiment with.</div>
&#13;
&#13;
&#13;