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

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值