我是使用 html+javascript+jQuery 的新手。我正在尝试使用 window.getSelection 来获取选定的文本,但这不起作用。任何人都可以为此提出解决方案。
提前致谢。
我是使用 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()");
我知道这是一个非常古老的问题,但是当我尝试解决相同或类似的问题时,我将其作为第一个搜索结果。我在这里没有找到解决方案,但一段时间后我意识到有时对于手机来说,单击和选择之间应该有一个短暂的超时,以使 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);
});
也许它可以为某人节省一些时间。
如果要在文本选择后立即调用函数,可以使用“selectionchange”事件:
document.addEventListener("selectionchange", handleSelection);
它适用于 android chrome 和 iOS safari。
尝试
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;
}