「用戶一選中文字就觸發某個動作」這個需求很常見——劃詞評論、劃詞翻譯、劃詞分享都屬於這一類。跨瀏覽器實現的核心難點在於取選中內容的 API 不統一,另外 input / textarea 裡的選中又是另一套機制。
select(document, tanchu);
/*=select[[
*
* 跨瀏覽器選中文字事件
*
* @param
* object o 響應選中事件的 DOM 對象,required
* function fn(sText, target, mouseP) 選中文字非空時的回調函數,required
* |-@param
* |-sText 選中的文字內容
* |-target 觸發 mouseup 事件的元素
* |-mouseP 觸發 mouseup 事件時鼠標坐標
*/
function select(o, fn){
o.onmouseup = function(e){
var event = window.event || e;
var target = event.srcElement ? event.srcElement : event.target;
if (/input|textarea/i.test(target.tagName) &&
/firefox/i.test(navigator.userAgent)) {
// Firefox 在文本框內選擇文字
var staIndex = target.selectionStart;
var endIndex = target.selectionEnd;
if(staIndex != endIndex){
var sText = target.value.substring(staIndex, endIndex);
fn(sText, target);
}
}
else{
// 獲取選中文字
var sText = document.selection == undefined
? document.getSelection().toString()
: document.selection.createRange().text;
if (sText != "") {
// 將參數傳入回調函數 fn
fn(sText, target);
}
}
}
}
function tanchu(txt, tar){
alert("文字屬於" + tar.tagName + "元素,選中內容為:" + txt);
}
原作者出處:https://momomolice.com/wordpress/archives/420.html
幾處細節值得留意:用 mouseup 而不是 selectionchange,是因為 mouseup 能拿到鼠標坐標,便於把工具提示定位到選區旁邊;對 Firefox 的 input/textarea 單獨處理,是因為它們支持 selectionStart / selectionEnd,而當時其他瀏覽器不支持;最後判斷 sText 非空,避免單純點擊(沒有選中任何內容)也觸發回調。
如果不需要監聽事件,只想在任意時刻拿到當前選中的文本,這個函數就夠了:
function getSelectedText()
{
if (window.getSelection)
{
// 這是最可能被標準化的方案
// getSelection() 返回一個 Selection 對象
return window.getSelection().toString();
}
else if (document.getSelection)
{
// 更早、更簡單的方案,直接返回字符串
return document.getSelection();
}
else if (document.selection)
{
// IE 專屬方案
// 這裡用到了 IE 的 selection 屬性與 TextRange 對象
return document.selection.createRange().text;
}
}
調用後即返回當前選取的文字。
原作者已不可考。
今天的寫法可以更簡單:現代瀏覽器統一支持 window.getSelection().toString(),而 document.addEventListener('selectionchange', ...) 已經能可靠地監聽選區變化(對輸入框也適用),不必再靠 mouseup 繞一圈。不過如果還需要同時拿到鼠標坐標來定位浮層,mouseup 的方案依然有它的價值。