How can I get the text that is going to be pasted in my html text editor?

[亡魂溺海] 提交于 2019-12-30 09:56:34

问题


I have a small text editor in my home page ( a textarea ) where I can paste text. How can I get this text in a variable before it would be pasted? I know that there is this function:

clipboardData.getData()

but it doesn't work in Firefox, and I want something for all the browsers.I am using HTML and Javascript.

thanks


回答1:


The short answer is that in general you can't get the text before it is pasted. What you can do is what big web-based WYSIWYG editors such as CKEditor and TinyMCE do, which is:

  1. Detect a Ctrl-v / shift-ins event using a keypress event handler
  2. In that handler, save the current user selection, add a <div> element off-screen (say at left -1000px) to the document, move the caret to be inside that div, thus effectively redirecting the paste
  3. Set a very brief timer (say 1 millisecond) in the event handler to call another function that retrieves the HTML content from the div and does whatever processing is required, removes the div from the document, restores the user selection and inserts the processed HTML.

Note that this will only work for keyboard paste events and not pastes from the context or edit menus. By the time the paste event fires, it's too late to redirect the caret into the div (in some browsers, at least).




回答2:


Getting the clipboard to work across all browsers is tricky and I believe it's safe to assume there's no way to make it work with only JavaScript, unless you're targeting one specific browser (usually IE). I used ZeroClipboard for this: http://code.google.com/p/zeroclipboard/ - it seems to do its job OK.



来源:https://stackoverflow.com/questions/4365833/how-can-i-get-the-text-that-is-going-to-be-pasted-in-my-html-text-editor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!