复制到所选选项的剪贴板值 [英] Copy to clipboard value of selected option
问题描述
我想使用jQuery或JavaScript将select
列表中所选选项的值复制到剪贴板.
I would like to copy to clipboard a value of selected option from select
list using jQuery or JavaScript.
我的html:
<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>
当用户选择任何选项时,该值应复制到剪贴板.我尝试使用clipboard.js
插件,但似乎无法与选择列表一起使用.
The value should be copied to clipboard when the user choose any option. I tried to use clipboard.js
plugin but it seems not working with select list.
推荐答案
您需要input
才能复制到剪贴板.我已经在change事件上创建了input
,并将值复制到剪贴板后将其删除.
You need input
to make copy to clipboard. I have create an input
on the change event and removed it after copying the value into clipboard.
基本上,您需要两个功能才能复制到剪贴板.即 select()
和 execCommand()
. select()
方法用于选择文本字段的内容.并且 execCommand()
方法为可编辑部分的选定部分.
Basically you need two function for copy to clipboard .i.e select()
and execCommand()
. The select()
method is used to select the contents of a text field. And execCommand()
method executes the specified command for the selected part of an editable section.
这是一个可行的示例.
$('#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>
这篇关于复制到所选选项的剪贴板值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!