在Vue和typescript中,我有自己的上下文菜单:
<context-menu id="context-menu" ref="ctxMenu">
<li @click="ctxMenuClickItem1($event)" v-on:mouseover="menuItemMouseover($event)" v-on:mouseleave="menuItemMouseleave($event)" v-bind:style="getMenuItemStyle()" >Open in TMS</li>
<li @click="ctxMenuClickItem2($event)" v-on:mouseover="menuItemMouseover($event)" v-on:mouseleave="menuItemMouseleave($event)" v-bind:style="getMenuItemStyle()" >Open in OnDemand</li>
<li @click="doCopy()" >Copy</li>
</context-menu>当我在页面上选择文本,然后单击上下文菜单(doCopy)中的第三项时,所选内容将消失。
Do copy函数如下所示:
doCopy: function () {
debugger;
var selection = window.getSelection();
},单击后选择为空: selection.toString()为"“
如何复制选中的文本?
发布于 2018-02-23 02:23:35
当您在上下文菜单中单击时,您的选择正在折叠(或重置),可能是因为移动了焦点。你需要在事件'contextmenu‘触发时获得选择,并在doCopy中恢复选择。JS示例:
var range = document.createRange();
docucment.addEventListener('contextmenu', (ev) => {
let selection = window.getSelection();
if(selection.rangeCount > 0) {}
range = selection.getRangeAt(0);
})
doCopy = function(){
let selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(range);
document.execCommand('copy');//save selection in buffer
}如果在contenteditable元素中选择文本,则需要在该元素中设置焦点。
https://stackoverflow.com/questions/48934126
复制相似问题