需求:当用户复制内容小于10时,直接执行复制操作,当用户复制内容超过10时,将用户复制内容追加版权所有字样。
//html
<div class="source">And paste it into this one.</div>
//js
const source = document.querySelector("div.source");
source.addEventListener("copy", (event) => {
const selection = document.getSelection();
const textContent = selection.baseNode.textContent;
const index = selection.anchorOffset;
const lastIndex = selection.focusOffset;
const currentText = textContent.substring(index, lastIndex);
const currentLen = currentText.length;
if (currentLen > 5) {
alert(`${currentText}超过最大复制字数`);
} else {
alert(`${currentText}版权所有转载注明出处`);
}
//内置API
console.log(selection.toString().toUpperCase());
console.log(selection.toString().length);
});
document.getSelection()
会返回一个当前光标选中的对象 其中anchorOffset字段代表光标起始位置 focusOffset字段代表光标结束为止 baseNode中包含当前元素下的全部内容
因此可以用substring截取到光标所选内容 同时也可以用内置的toString方法获取光标截取的内容和长度