复制所选选项的剪贴板值

5

我希望能够使用jQuery或JavaScript将

4个回答

5

你需要使用 input 才能把内容复制到剪贴板中。我已经在 change 事件上创建了一个 input 并在将值复制到剪贴板后将其删除。

基本上,你需要两个函数来复制到剪贴板,即 select()execCommand()select() 方法用于选择文本字段的内容。execCommand() 方法对可编辑部分中所选的部分执行指定的命令。

这是一个工作示例。

$('#choose-color').on('change', function(){
  var value= `<input value="${$(this).val()}" id="selVal" />`;
  $(value).insertAfter('#choose-color');
  $("#selVal").select();
  document.execCommand("Copy");
  $('body').find("#selVal").remove();
});
black
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="choose-color">
    <option value="red">RED</option>
    <option value="green">GREEN</option>
    <option value="yellow">YELLOW</option>
    <option value="black">BLACK</option>
</select>


这在Safari中不起作用(我使用的是17.0版本) - undefined
@martin execCommand已被弃用,而应使用navigator.clipboard.writeText("一个示例文本!"); - undefined
这在Safari中不起作用。我的相关问题在这里:https://stackoverflow.com/questions/77351436/writing-to-the-clipboard-onchange-of-a-dropdown-element-in-safari - undefined

2

你需要创建一个临时元素,比如 textarea,来设置 select 的值,并使用它来复制该值。在复制到剪贴板后,删除该 textarea 元素。

$('#choose-color').change(function(){
  var textarea = $('<textarea />');
  textarea.val($(this).val()).css({
    visibility: 'none'
  }).appendTo('body');
  textarea.focus().select();
   if (document.execCommand('copy')) {
      textarea.remove();
      return true;
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="choose-color">
    <option value="red">RED</option>
    <option value="green">GREEN</option>
    <option value="yellow">YELLOW</option>
    <option value="black">BLACK</option>
</select>


你能帮我解决这个问题吗?https://stackoverflow.com/questions/53374846/copy-to-clipboard-from-two-html-elements - Nancy
这在Safari 17.0中不起作用 - undefined

0
使用this中的copy()函数,您可以轻松地将下拉菜单复制到剪贴板中。
document.getElementById('choose-color').onclick = function () {
    let text = this.value;
    var input = document.createElement('input');
    input.setAttribute('value', text);
    document.body.appendChild(input);
    input.select();
    var result = document.execCommand('copy');
    document.body.removeChild(input)
    return result;
}

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接