简体   繁体   中英

jQuery selecting and replacing text in a div

So, im writing a very very basic text editor that is going to allow a user to do certain things such as change the colour of the text, make it bold or apply a header styling.

The first problem I have ran into is that selecting a word in text and applying bold to it will make it apply to the first instance of that word in the string when i do a replace, i need to be able to replace the actual item selected, by index, rather than a straight word replace.

Secondly is it possible for me to set tags within the div for the user to type within (click BOLD button and the user will type in and its set too bold etc, standard wysiwyg behaviour?)

My fiddle is here : http://jsfiddle.net/d7uvvywu/12/

I apologise, I am a beginner with jQuery.

My replace method for the text.

var span = '<'+htmlCon+'>' + highlight + '<'+htmlCon+'>';
var text = $('#textRegions_1__Text1').html();
$('#textRegions_1__Text1').html(text.replace(highlight, span));

What you need to accomplish is not get the selected text, but rather get the selected index start and selected index end.

Getting a selection from a textbox (text area) has already been well discussed here: How to get selected text from textbox control with javascript

So, as this was an editable div, the other answers in this thread didnt work for me, I ended up getting the index's of the selected text this way:

  var textComponent = document.getElementById('editer1');
  var selectedText;
  var range = window.getSelection().getRangeAt(0);
  var beforeSelectedRange = range.cloneRange();
  beforeSelectedRange.selectNodeContents(textComponent);
  beforeSelectedRange.setEnd(range.startContainer,range.startOffset);
  var startIndex = range.startContainer;
  var start = beforeSelectedRange.toString().length;
  var end = start + range.toString().length;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM