簡體   English   中英

window.getselection 在 android 中不起作用

[英]window.getselection is not working in android

我是使用 html+javascript+jQuery 的新手。 我正在嘗試使用 window.getSelection 來獲取選定的文本,但這不起作用。 任何人都可以為此提出解決方案。

提前致謝。

只需要在java腳本中完成你的工作的簡單代碼行

 //I am using below line of code which works in both android and web browsers.

function getSelectedText() {
    var selection = null;

    if (window.getSelection) {
        selection = window.getSelection();
    } else if (typeof document.selection != "undefined") {
        selection = document.selection;
    }

    var selectedRange = selection.getRangeAt(0);

    console.log(selectedRange.toString());
}

注意:不要在 post 中或在任何可運行接口內部調用此方法,因為 post 或任何可運行接口會延遲調用此方法(方法調用發生在瀏覽器選擇釋放后)。 只需像這樣調用這個方法

webView.loadUrl("javascript:getSelectedText()");

如果要在文本選擇后立即調用函數,可以使用“selectionchange”事件:

document.addEventListener("selectionchange", handleSelection);

它適用於 android chrome 和 iOS Safari。

我知道這是一個非常古老的問題,但是當我嘗試解決相同或類似的問題時,我將其作為第一個搜索結果。 我沒有在這里找到解決方案,但一段時間后我意識到有時對於手機,單擊和選擇之間應該有一個短暫的超時,以使 getSelection() 正常工作。

所以例如代替這個:

document.getElementById("element").addEventListener('click', function (event) {
    window.getSelection().selectAllChildren(this)
});

你應該像這樣使用一些想法:

document.getElementById("element").addEventListener('click', function (event) {
  setTimeout(function(passedThis) {
    window.getSelection().selectAllChildren(passedThis)
  }, 10, this);
});

也許它可以為某人節省一些時間。

嘗試

function getSelected() {
var text = "";
if (window.getSelection && window.getSelection().toString() && $(window.getSelection()).attr('type') != "Caret") {
    text = window.getSelection();
    return text;
} else if (document.getSelection && document.getSelection().toString() && $(document.getSelection()).attr('type') != "Caret") {
    text = document.getSelection();
    return text;
} else {
    var selection = document.selection && document.selection.createRange();
    if (!(typeof selection === "undefined") && selection.text && selection.text.toString()) {
        text = selection.text;
        return text;
    }
}
return false;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM