我想使用contentededitable并使用oncopy和onpaste函数来更改文本的颜色。当从contentedittable复制文本时,我希望文本是红色的,如果是粘贴的,那么我希望将文本颜色更改为绿色。这是可以实现的吗?我该如何实现?
HTML:
<html>
<head>
<audio id="copy" src="https://www.soundjay.com/button/sounds/beep-21.mp3" preload="auto"></audio>
<audio id="paste" src="https://www.soundjay.com/button/sounds/beep-22.mp3" preload="auto"></audio>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<button onclick="playCopy()">Copy Sound</button>
<button onclick="playPaste()">Paste Sound</button>
<p>Enter text here and copy</p>
<span id="content" oncopy="copy()" onpaste="paste()" contenteditable>Test words to copy and paste</span>
<br>
<br>
<p>This is the text in the clipboard</p>
<textarea id="clipBoard" readonly></textarea>
</body>
</html>
<script>
function playCopy() {
document.getElementById('copy').play();
}
function playPaste() {
document.getElementById('paste').play();
}
function copy(){
}
function paste(){
}
</script>发布于 2019-11-25 03:27:20
这不是最好的代码,但我希望它能给你一点启迪,让你继续前行。粘贴颜色也会有一些问题,因为当粘贴内容时,会先执行函数paste(),然后再粘贴内容。一旦我得到了更好的解决方案,我将编辑这个答案。
<html>
<head>
<audio id="copy" src="https://www.soundjay.com/button/sounds/beep-21.mp3" preload="auto"></audio>
<audio id="paste" src="https://www.soundjay.com/button/sounds/beep-22.mp3" preload="auto"></audio>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<style>
.color-red {
color: red;
}
.color-green {
color: green;
}
</style>
</head>
<body>
<button onclick="playCopy()">Copy Sound</button>
<button onclick="playPaste()">Paste Sound</button>
<p>Enter text here and copy</p>
<span id="content" oncopy="copy()" onpaste="paste()" contenteditable>Test words to copy and paste</span>
<br>
<br>
<p>This is the text in the clipboard</p>
<textarea id="clipBoard" readonly></textarea>
</body>
</html>
<script>
function playCopy() {
document.getElementById('copy').play();
}
function playPaste() {
document.getElementById('paste').play();
}
function copy() {
document.getElementById('content').classList.remove('color-green');
document.getElementById('content').classList.add('color-red');
}
function paste() {
document.getElementById('content').classList.remove('color-red');
document.getElementById('content').classList.add('color-green');
}
</script>
https://stackoverflow.com/questions/59020983
复制相似问题