去掉复制内容的样式操作方法

1,018 阅读1分钟

我们在上网的时候,经常用到复制粘贴的功能,

有时复制的内容是带有样式的,

而我们只想要文本内容,

这时候就要有去掉样式的操作,

以下方法可直接拿去使用

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
</head>
<style>
    .page3-emjoy5{
        width: 200px;
        height: 200px;
        border: 1px solid #ccc;
        margin: 30px;
    }
    .test{
        width: 200px;
        height: 200px;
        border: 1px solid #ccc;
        color: red;
        margin: 30px;
        background-color: green;
    }
    .meta{
        width: 200px;
        height: 200px;
        border: 1px solid rgb(17, 153, 119);
        margin: 30px;
    }
</style>
<body>
    <div class='page3-emjoy5' contenteditable>
        <p>去除样式</p>
    </div>
    <div class='test' contenteditable>
        <p>有样式</p>
    </div>
    <div class='meta' contenteditable>
        <p>不改变样式</p>
    </div>
    <script>
// console.log('$(".page3-emjoy5")', $(".page3-emjoy5"))
        $(".page3-emjoy5").on("paste", function (e) {
            textInit(e)
        });
        
        function textInit(e) {
            console.log('---paste--',e)
            e.preventDefault();
            var text;
            var clp = (e.originalEvent || e).clipboardData;
            if (clp === undefined || clp === null) {
                text = window.clipboardData.getData("text") || "";
                if (text !== "") {
                    if (window.getSelection) {
                        var newNode = document.createElement("span");
                        newNode.innerHTML = text;
                        window.getSelection().getRangeAt(0).insertNode(newNode);
                    } else {
                        document.selection.createRange().pasteHTML(text);
                    }
                }
            } else {
                console.log('text', text)
                text = clp.getData('text/plain') || "";
                if (text !== "") {
                    document.execCommand('insertText', false, text);
                }
            }
        }
    </script>
</body>

</html>``