How to modify pasted data ? Jquery

前端 未结 3 1604
囚心锁ツ
囚心锁ツ 2021-01-06 00:02

I followed this question JavaScript get clipboard data on paste event (Cross browser) to get the pasted data from the clipboard, but I used jquery instead. Now that I got t

相关标签:
3条回答
  • 2021-01-06 00:11

    Well, it depends on what element are you going to paste in. You could use jQuery or native Javascript to achieve!

    Maybe like $(targetNode).append(pastedData) or document.getElementById('targetNode').innerText = pastedData

    0 讨论(0)
  • 2021-01-06 00:18

    I found the answer and I am gonna share it. In order to sanitize the clipboard from html tags, you should paste this:

                 element.on('paste', function (e) {
                        e.preventDefault();
                        var text;
                        var clp = (e.originalEvent || e).clipboardData;
                        if (clp === undefined || clp === null) {
                            text = window.clipboardData.getData("text") || "";
                            if (text !== "") {
                                text = text.replace(/<[^>]*>/g, "");
                                if (window.getSelection) {
                                    var newNode = document.createElement("span");
                                    newNode.innerHTML = text;
                                    window.getSelection().getRangeAt(0).insertNode(newNode);
                                } else {
                                    document.selection.createRange().pasteHTML(text);
                                }
                            }
                        } else {
                            text = clp.getData('text/plain') || "";
                            if (text !== "") {
                                text = text.replace(/<[^>]*>/g, "");
                                document.execCommand('insertText', false, text);
                            }
                        }
                    });
    

    Credit: l2aelba

    0 讨论(0)
  • 2021-01-06 00:30

    Might be easier to let the paste proceed and update element immediately after. Would depend on use case also as cursor position could be lost this way

    $(':input').on('paste', function (e) {
        var $el = $(this); 
        setTimeout(function () {
            $el.val(function(){
                return this.value.replace(/foo/g, "bar"); 
            })
        });
    })
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <p>foo was here</p>
    <textarea></textarea>

    0 讨论(0)
提交回复
热议问题