如何扩大选择范围然后运行document.execCommand?

时间:2018-07-25 14:11:53

标签: javascript

仅是为了了解选择对象和范围对象如何在网页上工作,我想用鼠标选择一些文本,然后使用代码扩大选择范围,然后将该文本标记为粗体。

只要代码不触及范围,execCommand语句就可以将文本加粗。但是重新生成范围会导致execCommand无效。为什么会这样?

这是我运行的可扩大选择范围的函数:

function window_widenSelection( numChar )
{
  var sel = window.getSelection();
  range = sel.getRangeAt(0).cloneRange( );

  var startNode = range.startContainer ;
  var startOffset = range.startOffset ;
  var endNode = range.endContainer;
  var endOffset = range.endOffset ;

  range.setStart(startNode, startOffset);
  range.setEnd(endNode, endOffset + numChar ) ;
  range.collapse(true);
  sel.removeAllRanges();
  sel.addRange(range);
}

这是完整的代码:

<!-- demonstrate how to widen selection and highlight selected text -->
  <!-- http://192.168.1.170:10080/coder/tester/contentEditable/widenSelection.html -->

  <!DOCTYPE html>
  <html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>widen selection demo</title>
  </head>
  <body>

    <p>Select some text with the mouse, then click button to make the text bold.</p>
    <div>
        <button type="button" onclick="bold_click( )">bold selected text</button>
        &nbsp;
        <button type="button" onclick="widen_bold_click( )">widen, then bold selected text</button>
    </div>

    <br>
<div id="testDiv" contenteditable="true" autocomplete="off" autocorrect="off" 
          autocapiatlise="off" spellcheck="false" 
          style="padding: 5px 5px; border: 1px solid black;">
        This is a test <span style="color: blue">and this is blue</span>
        and this is back to black
      </div>

  </body>

  <script>

// -------------------------- formatDoc --------------------------------
function formatDoc(sCmd, sValue)
{
  document.execCommand(sCmd, false, sValue);

  var e1 = document.getElementById('text');
  if ( e1 )
    e1.focus();
}

function bold_click( ev )
{
  formatDoc('bold') ;
}

function widen_bold_click( ev )
{
  window_widenSelection(3) ;
  formatDoc('bold') ;
}

function window_widenSelection( numChar )
{
  var sel = window.getSelection();
  range = sel.getRangeAt(0).cloneRange( );

  var startNode = range.startContainer ;
  var startOffset = range.startOffset ;
  var endNode = range.endContainer;
  var endOffset = range.endOffset ;

  range.setStart(startNode, startOffset);
  range.setEnd(endNode, endOffset + numChar ) ;
 // range.collapse(true);
  sel.removeAllRanges();
  sel.addRange(range);
}

  </script>
  </html>

1 个答案:

答案 0 :(得分:0)

只是一个编码错误。创建范围后,我正在缩小范围。