Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

复制文本加上版权信息功能实现 #26

Open
chenyinkai opened this issue Feb 25, 2018 · 0 comments
Open

复制文本加上版权信息功能实现 #26

chenyinkai opened this issue Feb 25, 2018 · 0 comments

Comments

@chenyinkai
Copy link
Owner

chenyinkai commented Feb 25, 2018

有些网站为了维护版权信息, 用户在复制完成后, 发现粘帖出来的内容往往都还有一些作者名字之类的版权信息, 那么这样的功能是怎么实现的呢? 其实原理也是非常的简单,就是监听一下剪切板事件.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <div>前端好难学啊</div>
    <script>
        let oDiv = document.querySelector('div');
        oDiv.oncopy = function(e) { // 复制事件
            e.preventDefault();
            let copyMsg = window .getSelection() + '商业转载请注明出处。'; // window .getSelection() 表示选择的内容
            e.clipboardData.setData("Text", copyMsg); // 将复制信息添加到剪切板
        }
    </script>
</body>
</html>

原理: 监听文本复制事件, 并阻止事件默认行为, window .getSelection() 表示选中的文本内容, 再调用 clipboardData.setData() 方法将修改后的文本添加到剪切板

猛戳这里查看 clipboardData 对象的兼容性

注意

  • 在IE中,clipboardData对象是window对象的属性;
  • 在Chrome、Safari和Firefox 4+中,clipboardData对象是相应event对象的属性。
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant