Javascript selectionStart & selectionEnd

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3543476/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 05:05:48  来源:igfitidea点击:

Javascript selectionStart & selectionEnd

javascript

提问by Cory

I'm having some difficulties getting the script below to work with my text editor. I'm not sure what is wrong but selectionStart and selectionEnd are returning as undefined.

我在让下面的脚本与我的文本编辑器一起工作时遇到了一些困难。我不确定出了什么问题,但 selectionStart 和 selectionEnd 返回未定义。

Its suppose to get highlighted text in an editable iframe and then replace it.

它假设在可编辑的 iframe 中获取突出显示的文本,然后替换它。

 var textarea = document.getElementById('editor').contentWindow.document.body.innerHTML;

 if (document.selection)
 {
  textarea.focus();
  var sel = document.selection.createRange();
  alert(sel.text);
  sel.text = '<b>' + sel.text + '</b>';
 } else {
  var len = textarea.length;
  alert(len);
  var start = textarea.selectionStart;
  alert(start);
  var end = textarea.selectionEnd;
  alert(end);
  var sel = textarea.substring(start, end);
  alert(sel);
  var replaced = '<b>' + sel + '<b>';
  textarea =  textarea.substring(0,start) + replaced + textarea.substring(end,len);
 }

回答by Tim Down

The reason selectionStartand selectionEndare undefined is that your textareavariable contains a string, not a reference to a <textarea>element. You seem to be aware of this since elsewhere you're calling string methods such as substring. Just to be clear, strings have no selectionStartand selectionEndproperties; the objects that do are textareas and text inputs.

原因selectionStartselectionEnd未定义是您的textarea变量包含一个字符串,而不是对<textarea>元素的引用。您似乎已经意识到这一点,因为在其他地方您正在调用字符串方法,例如substring. 需要明确的是,字符串没有selectionStartselectionEnd属性;这样做的对象是文本区域和文本输入。