开发者

Transforming highlighted text inside an element using javascript

My goal is to be able to get the highlighted text within a document, but only if that text is within a given section, and then apply a certain style to that selected text after clicking a div tag. I'll explain what I mean:

So, having looked at window.getSelection() and document.selection.createRange().text, I attempted to use elmnt.getSelection() or elmnt.selection.createRange().text for some HTML element, elmnt. However, it doesn't seem to work, so that idea seems pretty null. This means I can't use this idea to determine the text that is highlighted within a given location. In case this doesn't make sense, essentially, I want html code that looks like this:

<body>
  <div id="content">Stuff here will not be effected</div>
  <div id="highlightable">Stuff here can be effected when highlighted</div>
  <div id="morecontent">Stuff here will also not be effected</div>
</body>

So that whenever I've highlighted text, clicking on a specified div will apply the proper CSS.

Now, on to the div tags. Basically, here's what I've got on that:

$('.colorpicker').click( function(e)
{
  console.log(getSelectedText());
}

Eventually, all I want this to highlight the selected text and have the div tag change the color of the selected text to that of the respective div tag that I've selected. Neither of these seems to be working right now, and my only guess for the reason of the div tag is that it unhighlights whatever I've got selected whenever I click on the div tag.

Fallbacks:

  • If there is more than one time that 'abc' is found on the page and I highlight to color 'abc', I would like that only that copy of 'abc' be highlighted.

I know this is a lot in one question, but even if I could get a little head start on this idea, my next personal project would be going a lot more smoothly. Than开发者_运维技巧ks. :)


The key in the solution to this will be working with the objects that represent text ranges in browsers, not the selected text itself. Look into methods available to you in both the FireFox Range and IE TextRange objects. Both of these contain means of replacing the selected text with your own markup (e.g. a span wrapping your selected text.)

  • For FF look into Range.getRangeAt(0).surroundContents(element)
  • For IE look into TextRange.pasteHTML()

I must warn you though... You'll probably end up down a scary path of browser quirks if you go through with this. Already from the get-go you're supporting two different objects for two of the major browsers.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜