略微加速

略速 - 互联网笔记

JS控制粘贴paste事件

2020-11-10 leiting (4849阅读)

标签 JavaScript

如果我们单纯地敲击键盘,输入的内容实际上都是纯文本。除了一些特殊情况,例如IE浏览器下的编辑框会自动把合乎条件的url地址自动加上链接。富文本污染的情况主要出现在复制粘贴的时候,于是,如果我们能在粘贴的时候,对剪切板中的内容进行HTML过滤,再手动插入内容,岂不就可以完美解决无法输入富文本的问题了吗!?

于是,鄙人不才,一番折腾,弄出了下面的代码:

$('[contenteditable]').each(function() {    // 干掉IE http之类地址自动加链接
    try {
        document.execCommand("AutoUrlDetect", false, false);
    } catch (e) {}
    
    $(this).on('paste', function(e) {
        e.preventDefault();
        var text = null;
    
        if(window.clipboardData && clipboardData.setData) {            // IE
            text = window.clipboardData.getData('text');
        } else {
            text = (e.originalEvent || e).clipboardData.getData('text/plain') || prompt('在这里输入文本');
        }
        if (document.body.createTextRange) {    
            if (document.selection) {
                textRange = document.selection.createRange();
            } else if (window.getSelection) {
                sel = window.getSelection();
                var range = sel.getRangeAt(0);                
                // 创建临时元素,使得TextRange可以移动到正确的位置
                var tempEl = document.createElement("span");
                tempEl.innerHTML = "&#FEFF;";
                range.deleteContents();
                range.insertNode(tempEl);
                textRange = document.body.createTextRange();
                textRange.moveToElementText(tempEl);
                tempEl.parentNode.removeChild(tempEl);
            }
            textRange.text = text;
            textRange.collapse(false);
            textRange.select();
        } else {            // Chrome之类浏览器
            document.execCommand("insertText", false, text);
        }
    });
});

http://www.zhangxinxu.com/wordpress/2016/01/contenteditable-plaintext-only/


北京半月雨文化科技有限公司.版权所有 京ICP备12026184号-3