Remove Styles from Text when Copying / Cutting usi

2019-02-13 01:17发布

问题:

Yo,

Alright been noodling on this one for a while: How copy/cut styled text without bringing along any style baggage (background-color, color, etc)?

Couple of routes of attacks that have been foiled:

  1. Style the text differently using ::select? Doesn't work, ::style isn't copied
  2. Style the selected text using jQuery's select binding This only works for inputs, not p, divs
  3. Intercept and remove style by binding an event to copy/paste using jQuery? Can't access the copied object to remove stuff, tried using e.preventDefault(); then returning the event object but that didn't work either
  4. Modify the clipboard data once it's been saved? Also no dice, most browsers wont let you into this without flash and some sort confirmation

Anyway, thoughts? Seems like it would be very useful for sites that have white background colors.

回答1:

I haven't got time to code up an example now, but you could do this for cut/copy triggered by keyboard shortcuts. It wouldn't work for cut/copy via context menu or Edit menu options because it relies on changing the user selection before the cut or copy event fires.

The steps:

  1. Handle the Ctrl-C and Ctrl-X keyboard shortcuts and the Mac equivalents.
  2. In this handler, create an off-screen element (absolute position and left -10000px, say) and copy the selected content into it. You can do this using window.getSelection().getRangeAt(0).cloneContents(), although you'll need separate code for IE < 9 and you should check the selection is not collapsed.
  3. Do whatever you like to to change the styling of the content of the off-screen element.
  4. Move the selection to encompass the content of the off-screen element so that it is this content that is cut or copied.
  5. Add a brief delay (a few milliseconds) using to window.setTimeout() that calls a function that removes the offscreen element and restores the original selection.


回答2:

Do you need this to occur in the browser... for each user?

If not - and it is just for you - then you can do this with Clipmate software.

http://www.clipmate.com/index.htm

It has a feature that removes all styling.



回答3:

Once you have triggered the copy or cut you can strip the html tags and only the text with some regex

var String = Sample.replace(/(<([^>]+)>)/ig,"");

Also if you have your stored text in a div with id "sample_div" Use var String=$('sample_div').text(''); to get only the text inside