更改粘贴文字的颜色

时间:2019-11-24 15:33:03

标签: javascript html

几天前,我问了this question。我遇到了无法更改要粘贴的文本颜色的问题。复制功能有效,并且我想对粘贴的文本执行相同的操作。将最新粘贴的文本更改为绿色,然后将其余文本(最后复制的文本除外)更改为默认颜色。

这是我的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" 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();
}
</script>

这是我的JavaScript:

$(document).ready(function() {
  var ctrlDown = false,
    ctrlKey = 17,
    cmdKey = 91,
    vKey = 86,
    cKey = 67;

  $(document).keydown(function(e) {
    if (e.keyCode == ctrlKey || e.keyCode == cmdKey) ctrlDown = true;
  }).keyup(function(e) {
    if (e.keyCode == ctrlKey || e.keyCode == cmdKey) ctrlDown = false;
  });

  // Document Ctrl + C/V 
  $(document).keydown(function(e) {
    var clip = document.getElementById("clipBoard");
    //copy
    if (ctrlDown && (e.keyCode == cKey)) {
      navigator.clipboard.readText()
        .then(text => {
          clip.value = text;
          document.getElementById('copy').play();

          var sel = window.getSelection();
          var range = 0;
          if (sel.rangeCount && sel.getRangeAt) {
            range = sel.getRangeAt(0);
          }
          // Set design mode to on
          document.designMode = "on";
          if (range) {
            sel.removeAllRanges();
            sel.addRange(range);
          }
          //reset all custom color edits
          $('font').removeAttr('color');
          // Colorize text
          document.execCommand("ForeColor", false, "red");
          // Set design mode to off
          document.designMode = "off";
        })
        .catch(err => {

        });
    }
    //paste
    if (ctrlDown && (e.keyCode == vKey)) {
        document.getElementById('paste').play();
      var text = document.getElementById("clipBoard").value;
      text.id = pasted;
    }
  });
});

这里是JSFiddle。 这仅适用于Chrome浏览器,谢谢!

0 个答案:

没有答案