Paste only plain-text into editable div

强颜欢笑 提交于 2019-12-04 10:06:26

This is tricky but not impossible. What you can do is quite involved and a bit of a hack that will work in Firefox 2+, IE 5.5+ and recent WebKit browsers such as Safari 4 or Chrome (untested on older versions). Recent versions of both TinyMCE and CKEditor use this technique on their iframe-based editors:

  1. Detect a ctrl-v / shift-ins event using a keypress event handler
  2. In that handler, save the current user selection, add a textarea element off-screen (say at left -1000px) to the document, turn contentEditable off and call focus() on the textarea, thus moving the caret and effectively redirecting the paste
  3. Set a very brief timer (say 1 millisecond) in the event handler to call another function that stores the textarea value, removes the textarea from the document, turns contentEditable back on, restores the user selection and pastes the text in.

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

zeah

For Ctrl+v I checked the content of the editable div on keyup. You can modify the content in that event. I was using nicedit text editor. This did not work for paste from right click-> paste. For 'paste' I had to modify the content using settimeout.

.addEvent('paste', function(e) {
        setTimeout(function(){
            if(condition){
                //modify content
            }
        },350);
    });

It can also be hacked by using javaScript. Hope this helps

I created an example here

<div contentEditable="true" id="clean-text-div"> </div>
<div id="clean-btn"> Clean Me</div>
<div id="message"> paste html content and clean background HTML for pure text</div>


$("#clean-btn").click(function(){
    $("#clean-text-div").text($("#clean-text-div").text());
    $("#message").text("Your text is now clean");
});
w00d

Did you try the event such as "paste" or "input" ? Then you can use regex to trip all html tag

$(document).bind('paste', function(e){ alert('pasting!') })

http://www.hscripts.com/scripts/JavaScript/remove-html-tag.php

There is a discussion on paste event you should also read :
Catch paste input

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