Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
419 views
in Technique[技术] by (71.8m points)

javascript - CreateTextRange is not working in Chrome

In this code, createRange is not working in Chrome. In IE it is working. Please help how to rectify in this. Is there any other property to work like create range. So that it will helpful for my project.

<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
      }
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

CreateTextRange is a Microsoft specific function, but there is an easy work around.

Use createRange instead as in this post for example:

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);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...