onclick复制或突出​​显示<code> to clipboard

时间:2017-04-09 23:11:30

标签: javascript jquery onclick markdown clipboard

When person clicks on any <code> element it'll auto highlight everything inside plus copy to clipboard. I'm writing articles and there are lots of copy / paste commands being used for SSH. It would be nice if I could shave off a few dozen clicks for the visitor. I get this error when I try the code below:

here is the error i receive

$(function () {
    $(document).on('click', 'code', function () {
        this.select();
    });
});

I write these articles in markdown, and when I export, it's just clean code. I would prefer if I didn't have to use Flash or add a class or id to the html. Instead, just assume everything inside <code> should be copied to clipboard on click.

I also just tried this, but still no luck.

<script type="text/javascript">
$('code').focus(function () {
  this.select();
  this.setSelectionRange(0, 9999);
}).mouseup(function (e) {
  e.preventDefault();
});
</script>

source

Selecting all text in HTML text input when clicked

http://jsfiddle.net/NNqyF/

2 个答案:

答案 0 :(得分:1)

The only way to do this is by creating a dumby textarea with the content copying it, then removing the textarea.

$(function () {
    $(document).on('click', 'code', function () {
      $(this).addClass("active")
       textarea =  $("<textarea>").val($(this).html()).height(0).appendTo(document.body).select();
        document.execCommand('copy');
       textarea.remove();
    });
});
code {
  background: #555;
  color:white;
}
.active {
  background:#3399ff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<code>test2</code>

答案 1 :(得分:1)

I've only tested this in chrome, but you can do the following:

$('code').on('click', function(e){
  var sel = window.getSelection()
  var r = document.createRange()
  r.selectNodeContents(e.target.closest('code'))
  sel.removeAllRanges()
  sel.addRange(r)
  document.execCommand('copy')
})

It does what yo want it to. Credit should go to these answers: How do I copy to the clipboard in JavaScript? and https://stackoverflow.com/a/2838358/6872682