JS获取当前选中内容

this.content=null;
this.range = null;
getHtml (win) {
      if (win) {
        let range = {};
        const createFragment = (html) => {
          if (html.toString()) {
            const div = document.createElement('div');
            div.appendChild(html.cloneContents());
            this.content = div.innerHTML;
            this.range = div;
          } else {
            this.range = this.content = null;
          }
        };
        if (win.getSelection) {
          try {
            range = win.getSelection().getRangeAt(0);
            createFragment(range);
          } catch (e) {
          }
        } else if (win.document.getSelection) {
          try {
            range = win.document.getSelection().getRangeAt(0);
            createFragment(range);
          } catch (e) {
          }
        } else if (win.document.selection) {
          try {
            range = win.document.selection.createRange();
            createFragment(range);
          } catch (e) {
          }
        }
      };
    },

getHtml(window)

  兼容谷歌、火狐、IE新版本

posted @ 2022-02-09 14:39  bomdeyada  阅读(471)  评论(0编辑  收藏  举报