[英]How to get single clicked word from textarea using JavaScript
是否可以在 IE 和 Firefox 中使用 jquery 或 javascript 從 textarea 獲取點擊的單詞。 目前我正在使用下面的代碼,它在 Chrome 中運行良好,但在 IE 和 Firefox 中根本不起作用。
<body>
<label for="result" style="display: none">Text</label>
<textarea id="result" rows="30" cols="100"></textarea>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$("#result").click(function() {
if($(this).val() !== null && $(this).val() !== ''){
var selection = window.getSelection();
selection.modify('extend', 'backward', 'word');
var end = selection.toString();
selection.modify('extend', 'forward', 'word');
var start = selection.toString();
selection.modify('move', 'forward', 'character');
var wordInput = end+start;
console.log(wordInput);
}
});
</script>
</body>
預期工作
讓我們假設一個帶有文本的文本區域:'Hello World'
當我單擊“Hello”中的任何位置時,它應該打印“Hello”而不是整個 textarea 值。 同樣適用於“世界”等。
IE 中的錯誤
SCRIPT438:對象不支持屬性或方法“修改”
任何人都可以幫助我嗎? 謝謝!
我猜這個代碼可以幫助你。
const getTheWord = (selectionStart, value) => { let arr = value.split(" "); let sum = 0 for (let i = 0; i < arr.length; i++) { sum += arr[i].length + 1 if (sum > selectionStart) return arr[i] } } const myArea = document.getElementById("myArea") myArea.value = "Hello world!" myArea.onclick = (e) => { let i = e.currentTarget.selectionStart console.log(getTheWord(i, myArea.value)) }
<textarea id="myArea"></textarea>
無需拆分所有文本。 這可能會導致性能不佳,因為我們不知道文本的長度。
試試這個:
function isSpace(character: string) {
return /\s/.test(character);
}
export function getSelectedWord(
selectionStart: number,
value: string
): string | null {
let start: number = selectionStart;
let end: number = selectionStart;
while (start - 1 >= 0 && !isSpace(value[start - 1]!)) {
--start;
}
while (end + 1 < value.length && !isSpace(value[end + 1]!)) {
++end;
}
const word = value.slice(start, end + 1);
return word || null;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.