createRange does not work in Chrome

萝らか妹 提交于 2019-12-24 07:31:24

问题


This works in IE9, but not in Chrome. I want to run this in Chrome. this is to find the word i am looking for when i put the word in Textbox. Could anyone solve this problem for me??

var n = 0;
var str = '';

function chk() {
  str = form1.kts.value;
  if (str == '') alert('none!');
  else ok();
}

function ok() {
  var found;
  var text = document.body.createTextRange();

  for (i = 0; i <= n && (found = text.findText(str)) != false; i++) {
    text.moveStart("character", 1);
    text.moveEnd("textedit");
  }
  if (found) {
    text.moveStart("character", - 1);
    text.findText(str);
    text.scrollIntoView();
    text.select();
    n++;
  } else {
    if (n > 0) {
      n = 0;
      ok();
    } else {
      alert("nothing.");
      form1.kts.value = '';
    }
  }
}

回答1:


createTextRange is only supported in IE (and some versions of Opera), to fix your problem you should probably use createRange instead for other browsers.

var n = 0,
    str = ''; 

function chk(){ 
    str = form1.kts.value; 
    if(str == '') {
        alert('none!');
    }else{
        ok();
    }
} 

function ok(){ 
    var found, text;
    if (document.createRange) {
        text = document.body.createTextRange();
        // do stuff for IE here
    }else{
        if( document.selectionStart ) {
            text = document.setSelectionRange(start, end);
            // do stuff for other browsers here
        }
    }

 .........​


来源:https://stackoverflow.com/questions/12911793/createrange-does-not-work-in-chrome

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!