在 Aurelia 中,如何根据按键事件获取文本区域内光标的坐标?

In Aurelia how to get co-ordinate of cursor inside textarea based on keypress event?

我添加了一个按键委托事件,但没有获取事件坐标。

我需要坐标来显示光标位置的自动建议列表,方法是更改​​它的顶部 css 和左侧 属性。

<div class="dropdown suggest  open" data-key="." css="display: ${autoSuggestTool.display}">
                                    <ul class="dropdown-menu" role="menu" css="top:${autoSuggestTool.top}; left: ${autoSuggestTool.left};">
                                        <li data-value="Test" class="active "><a href="#"><small>Test</small></a></li>                                                         </ul>
                                </div>
<textarea class="form-control" rows="5" cols="6" id="comment" value.bind="textAreaValue" keypress.delegate="autoSuggest($event)" placeholder="Type text "></textarea>

//.ts文件中的代码:

autosuggest(event){
        //here i need the pageX and PageY or offset to set the postion
        //this.autoSuggestTool.left = event.pageX;
        //this.autoSuggestTool.top= event.pageY;
        //**But in event i am not getting the co-ordinate of cursor inside textarea**
        //How to get the co-ordinate of cursor on key press in aurelia.
        }

由于您委托的是keypress,您接触的是KeyboardEvent类型的事件,因此其中没有坐标信息。

但是委派给 clickmousedown 等(类型 MouseEvent),您应该能够看到 pageX、clientX 等

最终能够使用光标位置并计算字符数和识别行号来获取光标在文本区域内的像素位置

     //Show and hide autoSuggestTool
     private showOverLayDiv(event) {
         this.index = 0;
         //get the cursor position inside the textarea
         this.getCursorPosition(event);
         //get the line number
         this.getLineNumber(event);
         //set the css left of the div
         this.autoSuggestTool.left = event.target.offsetLeft + (this.textAreaCursorPosition * 5) + "px";
         //set the css top of the div
         this.autoSuggestTool.top = (this.textAreaLineNumber * 24) + "px";
         this.autoSuggestTool.display = "block";


     }
     private getLineNumber(event)
     {
         this.textAreaLineNumber = event.target.value.substr(0, event.target.selectionStart).split("\n").length;

     }
     public getCursorPosition(event)
     {
         let pos = event.target.selectionStart;
         //set the text area cursor position 
         this.textAreaCursorPosition = pos - this.prevLine(event.target);


     }
     // get the location based on the characters in text area
     public prevLine(target)
     {
         let lineArr = target.value.substr(0, target.selectionStart).split("\n");

         let numChars = 0;

         for (var i = 0; i < lineArr.length - 1; i++) {
             numChars += lineArr[i].length + 1;
         }

         return numChars;
     }

//但是,如果在文本区域内添加了更多内容,则上面的代码向下滚动,然后自动建议列表 div 显示在底部,因为我在这里使用了增加的行数和文本区域得到滚动。结果,textarea 只保留在那里,现在开始滚动,但 Autosuggest div 根据行数显示在底部。 这只是此技术的缺点。