CreateTextRange无法在Chrome中使用

Bha*_*avi 14 javascript compatibility google-chrome

在此代码中,createRange无法在Chrome中使用.在IE中,它正在运行.请帮忙解决这个问题.是否有任何其他属性可以像创建范围一样工作.这样对我的项目很有帮助.

<script language=javascript>

    var isSelected;
    function markSelection ( txtObj ) {
      if ( txtObj.createTextRange ) {
        txtObj.caretPos = document.selection.createRange().duplicate();
        isSelected = true;
      }
    }

    function insertTag ( txtName, enclose ) {
        if(document.f_activity_email == null) {
            var tag = document.getElementById('EmailTokenID').value;
        }
        else {
            var formC = document.f_activity_email;
            var tag = formC.EmailTokenID.value;
        }
        var closeTag = tag;
        if ( enclose ) {
            var attribSplit = tag.indexOf ( ' ' );
            if ( tag.indexOf ( ' ' ) > -1 )
              closeTag = tag.substring ( 0, attribSplit );
        }
        if ( isSelected ) {
            var txtObj = eval ( "document.forms[0]." + txtName );
                if (txtObj.createTextRange && txtObj.caretPos) {
                    var caretPos = txtObj.caretPos;
                    caretPos.text = ( ( enclose ) ? "<"+tag+">"+caretPos.text+"</"+closeTag+">" : tag+caretPos.text );
                    markSelection ( txtObj );
                    if ( txtObj.caretPos.text=='' ) {
                     isSelected=false;
                    txtObj.focus();
                }
            }
      } else {
        // placeholder for loss of focus handler
      }
    }
Run Code Online (Sandbox Code Playgroud)

GôT*_*ôTô 14

CreateTextRange是Microsoft特定的功能,但有一个简单的解决方法.

createRange改为使用此帖子,例如:

if (document.selection) { //IE
    var range = document.body.createTextRange();
    range.moveToElementText(document.getElementById(containerid));
    range.select();
} else if (window.getSelection) { //others
    var range = document.createRange();
    range.selectNode(document.getElementById(containerid));
    window.getSelection().addRange(range);
}
Run Code Online (Sandbox Code Playgroud)


dan*_*y74 5

我在 node 的 JSDOM 和 codemirror(尝试使用 document.createRange)上遇到了这个问题

发生这种情况是因为 JSDOM 上不存在 ATM 上的 document.createRange (chrome),因此它尝试使用 document.body.createTextRange (IE) 代替并失败。

为了解决这个问题,我必须在我的单元测试设置中存根 document.createRange 函数,如下所示:

global.document.createRange = () => {
  return {
    setEnd: () => {},
    setStart: () => {},
    getBoundingClientRect: () => {}
  }
}
Run Code Online (Sandbox Code Playgroud)

有关于 JSDOM polyfilling document.createRange 的讨论:

https://github.com/tmpvar/jsdom/issues/399

在撰写本文时,这还没有发生。


小智 3

createTextRange 仅适用于 IE。

看看这个 http://help.dottoro.com/ljrvjsfe.php