接上一篇。
名字解释
selection对象
代表了当前激活选中区,即高亮文本块, 一个文档同一时间只能有一个选中区。选中区的可能为空或者包含文本和元素块。获取对象方式也不一致。
var xxxx;
if (window.getSelection) {// IE9、Firefox、Safari、Chromexxxx= window.getSelection();
} else if (document.getSelection) {
xxxx= document.getSelection();
} else if (document.selection) {//IE9以下支持
xxxx= document.selection.createRange().text;
}
console.log(xxxx);//range
是一种fragment(HTML片断),它包含了节点或文本节点的一部分。一般情况下,同一时刻页面中只可能有一个range,也有可能是多个range(使用Ctrl健进行多选,不过有的浏览器不允许,例如Chrome)。可以从selection中获得range对象,也可以使用document.createRange()方法获得。
更多的js 相关概念参考selection标准操作
代码解析(上篇文章的代码)
this.focus();// 点击事件后,simditor重新获取焦点
//simditor重新包装了selection
var $newNode, $newBlock, $nextBlock, $rootBlock;
// console.log(this['selection'].rootNodes())//是
$rootBlock = this['selection'].rootNodes().first();//顶层节点或块元素
$nextBlock = $rootBlock.next();//
if ($nextBlock.length > 0) {//selection有多个选中的 定节点或块元素
$newNode = $node.insertAfter($rootBlock);//在第一个选中的顶节点或块元素 后边插入
this['selection'].save();
this['selection'].restore();//常常和save()方法配合使用
} else if ($rootBlock[0].outerHTML == '<p><br></p>') {//如果是选中最后一行
$newNode = $node.insertBefore($rootBlock);//插入
this['selection'].setRangeAtStartOf($rootBlock);//设置光标
} else {//选中一行,非最后一行
$newNode = $node.insertAfter($rootBlock);
$newBlock = $('<p/>').append(this.util.phBr);
$newBlock.insertAfter($newNode);
this['selection'].setRangeAtStartOf($newBlock);
}
return this.trigger('valuechanged');
接口模块化开发,待续