网页版文本编辑器

项目中要实现选择文本改变样式,就是类似博客园中的效果。

考虑使用https://developer.mozilla.org/zh-CN/docs/Web/API/Document/execCommand ;document.execCommand实现。

当一个HTML文档切换到设计模式 designMode时,文档对象暴露 execCommand 方法,该方法允许运行命令来操纵可编辑区域的内容。大多数命令影响文档的选择(粗体,斜体等),而其他命令插入新元素(添加链接)或影响整行(缩进)。当使用contentEditable时,调用 execCommand() 将影响当前活动的可编辑元素。

语法

bool = document.execCommand('命令(比如bold)', false, '附带参数')

当点击加粗按钮的时候先判断文本长度,若为0,contenteditabel设为false,若不为0,则为true,此时document.execCommand才会生效,
// 获取选中的文本 function getSelectText() { var txt = ""; if(document.selection) { txt = document.selection.createRange().text; } else { txt = document.getSelection(); //txt = window.getSelection(); } return $.trim(txt.toString()); }


代码类似于下方效果
<body>
  <button onclick="test('bold')">加粗</button>
  <button onclick="test('italic')">斜体</button>
  <div>这是一段测试文本<span>dddd</span><span>aaaa</span></div>
<script>
  function test(e) {
      if(getSelectText().length==0){
        return
      }else{
        $('div').attr('contenteditable','true');
        var a=document.execCommand(e)
      }
  }
  function getSelectText() {  
    var txt = "";
    if(document.selection) {
      txt = document.selection.createRange().text;
    } else {
      txt = document.getSelection();
      //txt = window.getSelection();
    }
    return $.trim(txt.toString());
  }
</script>
</body>

猜你喜欢

转载自www.cnblogs.com/mocy-lv-tsf/p/9178797.html