如何恢复所选内容
How to restore selection?
我正在使用此代码将一些文本从<textarea>
复制到剪贴板:
function copy() {
var txtInput = document.getElementById('txtInput');
txtInput.select();
var success;
try {
success = document.execCommand('copy');
} catch(err) {
success = false;
}
if(!success) {
alert('Copy failed');
}
}
但是,我不想打乱用户的选择。我怎样才能把它恢复到以前的样子?
我只需要支持Safari的最新版本。
澄清:我想复制所有文本(就像此功能一样),但不更改其现有选择。
我现在明白了。这应该至少在Chrome 50+中有效。它将允许您突出显示文本、复制文本、保持突出显示并确保其在剪贴板上。
function getSelectionText() {
var txtInput = document.getElementById('txtInput');
if (txtInput.selectionStart != txtInput.selectionEnd) { // check the user has selected some text inside field
//get actual text
var selectedtext = txtInput.value.substring(txtInput.selectionStart, txtInput.selectionEnd);
//set original highlight
txtInput.setSelectionRange(txtInput.selectionStart, txtInput.selectionEnd)
return selectedtext;
}
}
function copy() {
//check our log to be sure
console.log(getSelectionText());
try {
window.document.execCommand('copy');
} catch (err) {
alert('Copy failed');
}
}
试试看:
https://jsfiddle.net/kwscmech/4/
这里有一个参考:http://www.javascriptkit.com/javatutors/copytoclipboard.shtml
更新:根据评论
function getSelectionText(cb) {
var txtInput = document.getElementById('txtInput');
if (txtInput.selectionStart != txtInput.selectionEnd) { // check the user has selected some text inside field
//get selected text
var selectedtext = txtInput.value.substring(txtInput.selectionStart, txtInput.selectionEnd);
var partial = {
start: txtInput.selectionStart,
end: txtInput.selectionEnd
};
//get all text
var allText = txtInput.select();
cb();
//set original highlight
txtInput.setSelectionRange(partial.start, partial.end);
}
}
function copy() {
console.log('copying')
getSelectionText(function() {
//check our log to be sure
console.log('callback');
try {
window.document.execCommand('copy');
} catch (err) {
alert('Copy failed');
}
})
}
https://jsfiddle.net/kwscmech/5/
相关文章:
- 为什么不是't窗口.恢复正常工作吗?(javascript/jquery)
- 如何临时暂停浏览器渲染,然后恢复整个页面
- NodeJS-readline暂停和恢复事件发射器(逐行读取)
- 谷歌地图劫持了iphone's滚动(触摸事件)-如何恢复
- 我希望在不替换现有变量的情况下恢复localStorage中的变量
- 克隆和恢复”;工具化的“;元素
- 如何暂停和恢复jquery间隔
- 在python中,我如何才能恢复被隐藏的元素的内容
- javascript恢复样式
- 在意外断电时恢复JS计时器
- 将JSON存储和恢复到此Ionic应用程序的最有效方法
- 在文本区域禁用javascript定义的keydown事件并恢复默认行为
- 将嵌套的主干模型存储并恢复到本地存储中
- 当客户端在JW Player中恢复丢失的连接时,会自动重新连接
- 从jquery对话框恢复原始数据,脚本不起作用
- 如何恢复Kinetic.js鼠标事件
- 需要编码帮助:向后拖放可恢复
- 如何在添加时间值时始终恢复到最长24小时
- 如何恢复所选内容
- 我如何暂停和恢复这个动画,它可以用纯CSS完成吗