【问题标题】:Typescript getSelection disappear打字稿getSelection消失
【发布时间】:2018-02-22 17:52:15
【问题描述】:

在 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) 中的第三项时,选择消失了。

复制功能如下:

 doCopy: function () {
  debugger;
  var selection = window.getSelection();
},

点击后选择为空:selection.toString() is ""

如何复制选中的文本?

【问题讨论】:

  • 在复制功能中获取选择状态,如果 selection.isCollapsed === true ,则无法复制文本。
  • 还有,请给出函数'doCopy'的代码
  • 我已经添加了整个doCopy函数好的,但是如何将isCollapsed设置为false?

标签: javascript typescript getselection


【解决方案1】:

当您单击上下文菜单时,您的选择正在折叠(或重置),可能是因为移动焦点。您需要在事件“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 元素中选择文本,则需要在该元素中设置焦点。

【讨论】:

猜你喜欢
  • 2020-12-06
  • 2018-05-10
  • 2020-11-18
  • 1970-01-01
  • 1970-01-01
  • 2022-01-25
  • 2020-06-12
  • 2016-08-03
  • 1970-01-01
相关资源
最近更新 更多