最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

selection api - Javascript selectionStart & selectionEnd - Stack Overflow

programmeradmin1浏览0评论

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.

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

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

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.

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

 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);
 }
Share Improve this question edited Nov 21, 2022 at 7:52 sideshowbarker 88.1k29 gold badges215 silver badges211 bronze badges asked Aug 22, 2010 at 21:26 CoryCory 7423 gold badges7 silver badges22 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 15

The reason selectionStart and selectionEnd are undefined is that your textarea variable 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 selectionStart and selectionEnd properties; the objects that do are textareas and text inputs.

发布评论

评论列表(0)

  1. 暂无评论