首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用oncopy和onpaste更改颜色

使用oncopy和onpaste更改颜色
EN

Stack Overflow用户
提问于 2019-11-25 02:25:51
回答 1查看 35关注 0票数 0

我想使用contentededitable并使用oncopyonpaste函数来更改文本的颜色。当从contentedittable复制文本时,我希望文本是红色的,如果是粘贴的,那么我希望将文本颜色更改为绿色。这是可以实现的吗?我该如何实现?

HTML:

代码语言:javascript
复制
<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>
EN

回答 1

Stack Overflow用户

发布于 2019-11-25 03:27:20

这不是最好的代码,但我希望它能给你一点启迪,让你继续前行。粘贴颜色也会有一些问题,因为当粘贴内容时,会先执行函数paste(),然后再粘贴内容。一旦我得到了更好的解决方案,我将编辑这个答案。

代码语言:javascript
复制
<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>

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59020983

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档