如何拆分span标签?

时间:2018-05-09 02:17:01

标签: javascript html dom

我最近和编辑一起遇到了什么问题?

我有一个范围

<span>123456789<span>

我选择了456个区域进行分割,我希望达到这种效果

<span>123</span>456<span>789</span>

我该怎么办?

1.用鼠标选择 enter image description here

2.点击粗体 enter image description here

3.Split效果 enter image description here

1 个答案:

答案 0 :(得分:0)

我想我找到了办法! ! !

&#13;
&#13;
window.onload = function(){
  var oBtn = document.querySelector('#btn');
  oBtn.onclick = function(){
    var range = getRangeAt();
    console.log(range.commonAncestorContainer.parentNode.nodeName);
    document.execCommand('RemoveFormat');
    range = getRangeAt();
    console.log(range.commonAncestorContainer.parentNode.nodeName);
  }
}

function getRangeAt(win) {
    var _selection, //选取对象
        _range //光标对象
    ;
    win = win || window; //获取创建光标的域
    //html5得到光标的处理
    if (win.getSelection) {
        _selection = win.getSelection(); //获取选取对象
        //当获取选取中有光标的处理
        if (_selection.rangeCount) {
            _range = _selection.getRangeAt(0); //返回选区的处理
        }
    }
    //ie系列的处理,ie系列不支持win.getSelection,有自己独特的属性
    else {
        _selection = win.document.selection; //获取选取对象
        _range = _selection.createRange(); //光标对象
    }
    return _range; //光标的处理
}
&#13;
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
  <div contenteditable="true"> 
    <span style="font-weight:bold">Selected part</span>
  </div>
  <button id="btn">split</button>
</body>
</html>
&#13;
&#13;
&#13;