简体   繁体   English

(select) 事件不适用于 div 元素

[英](select) event doesn't work for div elements

The user can type a text in a div that has the attribute contenteditable="true" and they can also select a text.用户可以在具有属性contenteditable="true"div中键入文本,他们还可以选择文本。 I now would like to output the selected text.我现在想输出选定的文本。

This is what I have tried:这是我尝试过的:

<div (select)="getSelectedText()" contenteditable="true" #editor id="editor"></div>
getSelectedText(): void {
  console.log(window.getSelection());
}

This is not working, probably because (select) is not available for div .这不起作用,可能是因为(select)不适用于div This is what the documentation of it says:这就是它的文档所说的:

Element: select event元素:选择事件

The select event fires when some text has been selected.选择某些文本时会触发 select 事件。

... ...

The event is not available for all elements in all languages.该事件不适用于所有语言的所有元素。 For example, in HTML, select events can be dispatched only on form <input type="text"> and <textarea> elements.例如,在 HTML 中, select事件只能在表单<input type="text"><textarea>元素上发送。

Is there an alternative to this in Angular?在 Angular 中是否有替代方案?

There is not much you can do but to listen either mouse, either to keyup event:除了听任一鼠标或 keyup 事件外,您无能为力:

HTML HTML

<div (keyup)="getSelectedText()" (mouseup)="getSelectedText()" contenteditable="true" #editor id="editor"></div>

TS TS

  getSelectedText(){
    console.log(document.getSelection()?.toString())
  }

Demo 演示

You should use a mouseup and mouseout event in your div and then call window.getSelection().toString() to get the selected text.您应该在 div 中使用 mouseup 和 mouseout 事件,然后调用 window.getSelection().toString() 来获取选定的文本。

<div (mouseup)="getSelectedText()" (mouseout)="getSelectedText()"contenteditable="true" #editor id="editor"></div>

getSelectedText(): void {
   if (window.getSelection) {
        window.getSelection().toString();
    }
}

Ref : Get the Highlighted/Selected text参考: 获取突出显示/选定的文本

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM