关于老版本ie的兼容可参照https://www.jianshu.com/p/c85958c277b7
或使用插件 clipboardjs (注意在模态框中使用时因焦点变化,需手动设置container属性或使用$refs实例化)或 clipboard-copy
方法
window.getSelection()获得selection对象
- anchorNode : “起点”节点。
- anchorOffset : “起点”在anchorNode中的偏移量。
- focusNode : “结束点”节点。
- focusOffset : “结束点”在focusNode中的偏移量。
- isCollapsed : “起点”和“结束点”是否重合。
- rangeCount : 包含range对象的数目,一般只存在一个range,Ctrl健配合使用可以有多个(但是chrome禁止ctrl多选)。
- window.getSelection().toString()可以获得当前选中的string值
select 选中
document.getElementById('data').select();
@仅对input或textarea生效
@只能在事件中触发(如click,focus等),无法直接或在计时器中触发
@使目标中的值被选中
@使用jquery亦可
setSelectionRange 改变选中区域
document.getElementById('data').setSelectionRange(1,1);
@改变选中的区域,必须在焦点状态下执行(如input被focus时,或执行了select方法)
@起始位置到结束位置,从第一个字符之前为0开始计数,如果两个参数相同,则为移动光标到该位置
@jquery无该方法
@IE9以上兼容
execCommand
对input,textarea,以及contentEditable="true"的元素均有效
document.execCommand("Copy");
//复制选定文本到剪切板
document.execCommand("insertText", "false", "111")
//在光标所在位置插入文本(如有select区域则被覆盖)
//bool显示用户面板默认false,且当前各浏览器未支持true
document.execCommand("forwardDelete")
//删除光标所在位置字符,等于按了一次删除键
cut和copy命令因浏览器不同而不同,而且不同时期,其启用条件也不尽相同。
在部分浏览器中只能通过实际的用户操作触发(不能在ajax回调里触发),因此需要直接放在事件中,或改用同步的ajax(不推荐)
可以通过document.execCommand判断是否存在该方法,document.execCommand()的返回值判断是否调用成功
if (document.execCommand) {
if (document.execCommand("Copy")) {
//复制成功
} else {
//复制失败
}
}
取消选中
var clearSlct = "getSelection" in window ? function () {
window.getSelection().removeAllRanges();
} : function () {
document.selection.empty();
};
clearSlct();
事件
onselectionchange
监听每次选中内容改变
<body>
<div id="content">
aaaaaaaaaaaaabbbbbbbbbccccccccccccc
</div>
<button class="btn">点击改变</button>
</body>
<script src="./lib/jquery-2.0.3.min.js"></script>
<script type="text/javascript">
$(function () {
var selectedText
var tempStr1
var tempStr2
document.addEventListener("selectionchange", function () {
if (window.getSelection() != '') {
var textObj = document.getElementById("content");
selectedText = window.getSelection().toString();
tempStr1 = textObj.innerText;
} else {
return
}
});
$('.btn').on('click', function () {
document.getElementById("content").innerHTML = tempStr1.replace(selectedText, "<b>" +
selectedText + "</b>")
})
});
</script>