+
95
-

回答

在JavaScript中实现复制文章时自动将文章内容变成乱码,可以通过监听复制事件并在复制内容中插入乱码来实现。以下是一个简单的示例代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Copy Protection</title>
    <style>
        #content {
            width: 80%;
            margin: 0 auto;
            padding: 20px;
            border: 1px solid #ccc;
        }
    </style>
</head>
<body>
    <div id="content">
        <h1>Sample Article</h1>
        <p>This is a sample article. Copying this text will result in gibberish.</p>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
    </div>

    <script>
        document.addEventListener('copy', function(event) {
            // Get the selected text
            const selection = window.getSelection();
            const selectedText = selection.toString();

            // Generate gibberish text
            const gibberish = Array(selectedText.length).fill('*').join('');

            // Create a temporary element to hold the gibberish text
            const tempElem = document.createElement('div');
            tempElem.style.position = 'absolute';
            tempElem.style.left = '-9999px';
            tempElem.textContent = gibberish;
            document.body.appendChild(tempElem);

            // Select the gibberish text
            const range = document.createRange();
            range.selectNode(tempElem);
            selection.removeAllRanges();
            selection.addRange(range);

            // Restore the original selection after a short delay
            setTimeout(() => {
                selection.removeAllRanges();
                selection.addRange(range);
                document.body.removeChild(tempElem);
            }, 0);
        });
    </script>
</body>
</html>
解释监听复制事件:使用 document.addEventListener('copy', function(event) { ... }) 来监听复制事件。获取选中的文本:使用 window.getSelection() 获取用户选中的文本。生成乱码:创建一个与选中文字长度相同的乱码字符串。创建临时元素:创建一个临时元素来存放乱码字符串,并将其位置设置为屏幕外,以避免影响页面布局。选择乱码文本:使用 range.selectNode(tempElem) 选择临时元素中的乱码文本。恢复原始选择:在复制事件结束后,恢复原始选择,并移除临时元素。

这种方法可以在用户复制文本时,将复制的内容替换为乱码,从而达到一定的防复制效果。然而,这种方法并不能完全防止内容被复制,因为用户仍然可以通过其他方式(如截图)来获取原始内容。

如果js被禁用,那么你只能自己弄一套字体体系,字体的显示字体与文本有一个对应关系,这样文章看起来是正常,但是复制的却是另外一种文本。

网友回复

我知道答案,我要回答