简体   繁体   English

如何使用javascript显示基于光标位置的下拉菜单?

[英]How to display a dropdown menu based on cursor position using javascript or react?

I am new to programming and want to check if the string contains @ character before or after the cursor position. 我是编程新手,想检查字符串在光标位置之前还是之后是否包含@字符。

If the @ is present only before cursor position in the input field then get the complete string after @ . 如果@仅在输入字段中的光标位置之前出现,则在@之后获取完整的字符串。

If the @ is present before and after the cursor position then get the string from @ (that is the one before cursor position) until white space. 如果@前和光标位置之后存在,则得到的字符串@ (即前光标位置的一个),直到空白。

String example: "I am @u @user1" , here cursor position is at index 8. 字符串示例: "I am @u @user1" ,此处光标位置在索引8处。

What I have tried: I am using event.target.selectionStart to get the cursor position and then the lastindexOf('@') in the string. 我尝试了什么:我正在使用event.target.selectionStart来获取光标位置,然后是字符串中的lastindexOf('@')

if (event.target.selectionStart > event.target.value.lastIndexOf('@')) {
    /*this means there is no @ after cursor position*/
    string =    event.target.value.substr(event.target.value.lastIndexOf('@') +1);
}

But I am not sure how to find out if there is another @ character before cursor position and how to get the string after @ that is before the cursor position. 但是我不确定如何确定光标位置之前是否还有另一个@字符,以及如何获取光标位置之前@之后的字符串。

I am quite confused and don't know how to proceed further. 我很困惑,不知道如何进一步。 Could someone help me with this? 有人可以帮我吗? Thanks. 谢谢。

Well you're on the right track. 好吧,您走在正确的轨道上。

You just have to be more specific in your conditionnals. 您只需要在条件方面更具体。

 const test = document.querySelector('input'); test.addEventListener('keyup', function(event) { if (event.target.selectionStart > event.target.value.indexOf('@') && event.target.selectionStart > event.target.value.lastIndexOf('@')) { console.log(event.target.value.substring(event.target.value.indexOf('@'))); } if (event.target.selectionStart <= event.target.value.indexOf('@') && event.target.selectionStart <= event.target.value.lastIndexOf('@')) { console.log('after cursor'); } if (event.target.selectionStart > event.target.value.indexOf('@') && event.target.selectionStart <= event.target.value.lastIndexOf('@')) { console.log(event.target.value.substring(event.target.value.indexOf('@'), event.target.value.lastIndexOf('@'))); } }) 
 <input value="I am @u @user1"> 

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

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