js 浏览器中监听粘贴内容并处理

粘贴时对剪贴板的内容进行处理

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <div id="box" contenteditable="true" style="width:600px;min-height:300px;text-align:justify ;margin:100px auto;border: 1px solid orange;">中国青年网北京8月10日电(记者 曾繁华) “知伯以国士遇臣,臣故国士报之。”《战国策》中这句名言堪称中国“礼贤下士”“士为知己者死”文化传统的生动写照。历朝历代,“国士”一向被视作社稷的金梁玉柱;如今,“国士”一词可以视作各阶层、各行业人才的统称。新时代的“国士”们,一直受到党和政府乃至社会的高度关怀、重视与认可。
    </div>
    <div id="tip" style="width:600px;min-height: 200px;margin: 20px auto;border:1px solid #ddd;"></div>
    <script type="text/javascript" src="../js/jq1.9.js"></script>
    <script>
        document.querySelector('#box').addEventListener('paste', (e) => {
            // Prevent the default pasting event and stop bubbling
            e.preventDefault();
            e.stopPropagation();

            // Get the clipboard data
            let paste = (e.clipboardData || window.clipboardData).getData('text/html');

            // Do something with paste like remove non-UTF-8 characters
            paste = paste.replace(/style/gi, 'data-style');

            // Find the cursor location or highlighted area
            const selection = window.getSelection();

            // Cancel the paste operation if the cursor or highlighted area isn't found
            if (!selection.rangeCount) return false;
            var div = document.createElement("div");
            div.innerHTML = paste;
            // Paste the modified clipboard content where it was intended to go
            selection.getRangeAt(0).insertNode(div);
            //$("#tip").html(paste)
        });
    </script>
</body>

</html>

参考:MDN

猜你喜欢

转载自blog.csdn.net/bluelotos893/article/details/81586699
今日推荐