Remove Styles from Text when Copying / Cutting using CSS or Javascript

烂漫一生 提交于 2019-11-30 12:42:08

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.

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.

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

Given current browser capabilities, you can intercept the copy event, get the selection without style, and put that into the clipboard.

I've tested this code with Chrome/Safari/Firefox. Believe is should work on MS browsers as well.

document.addEventListener('copy', function(e) {
  const text_only = document.getSelection().toString();
  const clipdata = e.clipboardData || window.clipboardData;  
  clipdata.setData('text/plain', text_only);
  clipdata.setData('text/html', text_only);
  e.preventDefault();
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!