有没有办法选择一个多行asp:textbox中的所有文本,并使用c#通过单击按钮将其复制到客户端剪贴板?
提前谢谢你。
发布于 2016-06-13 16:51:26
你可以使用document.execCommand("copy");
,但要知道这主要是由新浏览器支持的,据我所知没有对Safari的支持:
<head runat="server">
<title></title>
<script src="https://code.jquery.com/jquery-1.12.2.min.js"></script>
<script type="text/javascript">
$(function () {
$("#btnCopy").click(function () {
var id = "#" + "<%= txtText.ClientID %>";
try {
$(id).select();
document.execCommand("copy");
}
catch (e) {
alert('Copy operation failed');
}
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:TextBox ID="txtText" runat="server" Text="Some sample text to copy"></asp:TextBox>
<button id="btnCopy">Copy</button>
</form>
</body>
经测试,可与以下浏览器配合使用:
发布于 2016-06-13 17:32:44
我认为@Denis Wessels的答案很棒,但使用了普通的textarea而不是asp:TextBox,因此我想编写自己的包含asp:TextBox控件的代码。
假设您有一个多行文本区,其中包含asp:TextBox服务器控件和一个用于将内容复制到剪贴板的按钮:
<asp:TextBox ID="TextArea" runat="server" TextMode="MultiLine">
<button id="copy">Copy to Clipboard</button>
使用jQuery和类似如下的JS函数:
<script type="text/javascript">
$(document).ready(function () {
$("#copy").click(function() {
// use ASP .NET ClientID if you don't sure
// for ASP .NET 4.0 and above, set your ClientID with static mode
var textarea = "<%= TextArea.ClientID %>";
$(textarea).select();
$(textarea).focus(); // set focus to this element first
copyToClipboard(document.getElementById(textarea));
});
});
function copyToClipboard(elem)
{
var result;
var target = elem;
startPoint = elem.selectionStart;
endPoint = elem.selectionEnd;
var currentFocus = document.activeElement;
target.setSelectionRange(0, target.value.length);
try
{
// this may won't work on Safari
result = document.execCommand("copy");
}
catch (e)
{
return alert("Copy to clipboard failed: " + e);
}
// returning original focus
if (currentFocus && typeof currentFocus.focus === "function") {
currentFocus.focus();
}
elem.setSelectionRange(startPoint, endPoint);
return result;
}
</script>
略有更改的引用:https://stackoverflow.com/a/22581382、https://stackoverflow.com/a/30905277
请注意,对于ASP .NET 4及更高版本,您可以设置静态ClientID:
<asp:TextBox ID="TextArea" runat="server" TextMode="MultiLine" ClientID="TextArea" ClientIDMode="Static">
因此,您可以直接使用$("#TextArea")
而不是$("<%= TextArea.ClientID %>")
。
发布于 2016-06-13 16:50:41
您可以使用此类:System.Windows.Forms.Clipboard.SetText(..)
<=将文本设置为剪贴板,在SetText()中,您可以放入textbox.Text
以从多行asp.net文本框中获取文本。
https://stackoverflow.com/questions/37784995
复制相似问题