复制html< select multiple>中的值到剪贴板 [英] Copy values from html <select multiple> to clipboard

查看:89
本文介绍了复制html< select multiple>中的值到剪贴板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个选择元素

<select multiple="multiple" size="10" id="selection">  
    <option value="test1">Test1</option> 
    <option value="test2">Test2</option>
</select>

用户抱怨是因为他们无法将值复制到剪贴板。有没有办法让用户可以复制?我创建了这个JSfiddle,但在我看来它不是一个好的解决方案。

A user is complaining because they cannot copy values to their clipboard. Is there any way to make it so users can copy? I created this JSfiddle however it is not a good solution in my opinion.

http://jsfiddle.net/22gy9/4/

推荐答案

我认为不可能用按钮完成(如你的例子)。然而,通过执行如下所述的操作有点可能。

I think it cannot be done with a button (like in your example). However it is somewhat possible by doing something like described below.

首先我们需要一个文本字段,该值是可编辑的并且可以选择(这将作为我们的剪贴板) )。我们需要的第二件事是检测用户是否按下CTRL(对于CTRL + C)。所以基本的想法是将选定的值复制到我们的文本字段,当用户按下CTRL时,我们选择文本字段的内容。然后通过按C,用户在我们的文本字段而不是select元素上执行复制命令。

First we need a textfield, which value is editable and can be selected (this will work as our "clipboard"). A second thing we need is a way to detect if user presses CTRL (for CTRL+C). So the basic idea is to copy selected values to our textfield and when the user presses CTRL we select the contents of our textfield. Then by pressing C the user is performing a copy command on our textfield instead of the select-element.

这是一个基本实现(检查下面的jsfiddle)。您可以根据自己的需要对其进行微调:)

Here's a basic implementation (check the jsfiddle below). You can fine tune it to match your needs :)

HTML

< select multiple =multiplesize =10id =selectiononkeydown =keydown(event)onchange =changeClipboardValue(this)>

< option value =test1> ;测试1< /选项>
< option value =test2> Test2< / option>
< / select>
< input type =textid =clipboardonkeyup =keyup(event)/>

JavaScript

JavaScript

function changeClipboardValue(selectBox){
var clipboard = document.getElementById(clipboard);
var text =;
for(i = 0; i< selectBox.length; i ++){
if(selectBox.options [i] .selected)text + = selectBox.options [i] .value +, ;
}
clipboard.value = text;
}

function keydown(e){
if(e.keyCode == = 17){
var clipboard = document.getElementById(clipboard);
clipboard.select();
}
}

功能键(e){
if( e.keyCode === 17){
var selectBox = document.getElementById(selection);
selectBox.focus();
}
}

可能想要添加CSS来隐藏剪贴板字段
#clipboard {width:1px; height:1px; padding:0; position:absolute; left:-9999px;}

Might want to add CSS to hide the clipboard field #clipboard {width: 1px;height: 1px;padding:0;position:absolute;left:-9999px;}

< a href =http://jsfiddle.net/LubZt/ =nofollow> http://jsfiddle.net/LubZt/

更新:
http://jsfiddle.net/Kcv6j/ 这个版本在按住CTRL时效果更好选择多个项目。

UPDATE: http://jsfiddle.net/Kcv6j/ this version works better when holding CTRL to select multiple items.

这篇关于复制html&lt; select multiple&gt;中的值到剪贴板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆