2017-04-03 46 views
1

我有一個作出反應的應用程序,顯示一些跨度:選擇文本和高亮選擇或獲得選擇值(反應)

<span>Hello</span> <span>my</span> <span>name</span> <span> is </span> ... 

我想用戶用鼠標選擇文本,像這樣Hello my Name is

..然後得到選定的值,或突出顯示文字等。 我如何在React中執行此操作?我不確定要使用哪些事件處理程序以及如何獲取當前選擇!一個最小的例子或提示將不勝感激!

+0

的[獲取高亮顯示/選定的文本]可能的複製(http://stackoverflow.com/questions/5379120/get-the-highlighted-selected-text) – lustoykov

+0

我不認爲這是重複的,因爲我在這裏具體詢問React - 但我想沒有React特定的解決方案呢? –

+0

不需要特定的反應解決方案,因爲在所有JS框架/方法中都有更強大和通用的解決方案 - https://developer.mozilla.org/en-US/docs/Web/API/Window/getSelection – lustoykov

回答

0

沒有作出反應,具體的解決方案這一點。只需使用window.getSelection API。


要輸出突出顯示的文本來看window.getSelection.toString()

+0

這不回答這個問題。 – Yeats

1

這是在文本區域中選定的值顯示。你可以試試這個。我的文本在textarea。你可以嘗試跨度。我試着用它工作得很好。我希望這將是對你有幫助...

function getSelectionTxt() { 
 
    var text = ""; 
 
    var activeEl = document.activeElement; 
 
    var activeElTagName = activeEl ? activeEl.tagName.toLowerCase() : null; 
 
    if (
 
     (activeElTagName == "textarea") || (activeElTagName == "input" && 
 
     /^(?:text|search|password|tel|url)$/i.test(activeEl.type)) && 
 
     (typeof activeEl.selectionStart == "number") 
 
    ) { 
 
     text = activeEl.value.slice(activeEl.selectionStart, activeEl.selectionEnd); 
 
    } else if (window.getSelection) { 
 
     text = window.getSelection().toString(); 
 
    } 
 
    return text; 
 
} 
 

 
document.onmouseup = document.onkeyup = document.onselectionchange = function() { 
 
    document.getElementById("sel").value = getSelectionTxt(); 
 
};
Selection: 
 
<br> 
 
<textarea id="sel" rows="3" cols="50"></textarea> 
 
<p>Please select some text.</p> 
 
<input value="Some text in a text input"> 
 
<br> 
 
<input type="search" value="Some text in a search input"> 
 
<br> 
 
<input type="tel" value="4872349749823"> 
 
<br> 
 
<textarea>Some text in a textarea</textarea><br/> 
 
<span>Hii,</span><span>Urvish</span><span>How's</span><span>You?</span>