[英]React - JavaScript: How to properly position a dropdown menu on top of a Google Map
[英]How to display a dropdown menu based on cursor position using javascript or react?
我是編程新手,想檢查字符串在光標位置之前還是之后是否包含@
字符。
如果@
僅在輸入字段中的光標位置之前出現,則在@
之后獲取完整的字符串。
如果@
前和光標位置之后存在,則得到的字符串@
(即前光標位置的一個),直到空白。
字符串示例: "I am @u @user1"
,此處光標位置在索引8處。
我嘗試了什么:我正在使用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);
}
但是我不確定如何確定光標位置之前是否還有另一個@
字符,以及如何獲取光標位置之前@
之后的字符串。
我很困惑,不知道如何進一步。 有人可以幫我嗎? 謝謝。
好吧,您走在正確的軌道上。
您只需要在條件方面更具體。
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.