之前几乎没有JavaScript,但我尝试了几种方法将尖号(结束)放置在JavaFX HTMLEditor中,但没有成功。
例如,我已经尝试过:contenteditable, set caret at the end of the text (cross-browser)通过在placeCaretAtEnd(el)
部分中添加函数<script>
,如下所示(我在这里省略了<script>
部分):
<html>
<head>
<style>
</style>
</head>
<body onLoad='document.body.focus();' onfocus='placeCaretAtEnd(document.body);' contenteditable='true'>
</body>
</html>
(我通过HTMLEditor.setHtmlText进行了设置)
但是,插入符号始终停留在开头。是否有人成功将插入符号放置在JavaFX HTMLEditor中?
最佳答案
好吧,我终于开始工作了。我不确定onfocus
为什么不起作用。
public void requestFocus() {
HTMLEditorSkin skin = (HTMLEditorSkin) editor.getSkin();
try {
Field f = skin.getClass().getDeclaredField("webView");
f.setAccessible(true);
WebView wv = (WebView) f.get(skin);
Platform.runLater(() -> {
wv.requestFocus();
wv.getEngine().executeScript("document.body.focus()");
wv.getEngine().executeScript(
"var el = document.body;\n" +
"if (typeof window.getSelection != \"undefined\"\n" +
" && typeof document.createRange != \"undefined\") {\n" +
" var range = document.createRange();\n" +
" range.selectNodeContents(el);\n" +
" range.collapse(false);\n" +
" var sel = window.getSelection();\n" +
" sel.removeAllRanges();\n" +
" sel.addRange(range);\n" +
" } else if (typeof document.body.createTextRange != \"undefined\") {\n" +
" var textRange = document.body.createTextRange();\n" +
" textRange.moveToElementText(el);\n" +
" textRange.collapse(false);\n" +
" textRange.select();\n" +
" }");
});
} catch (NoSuchFieldException | IllegalAccessException e) {
e.printStackTrace();
}
}
关于javascript - 在JavaFX HTMLEditor中定位插入符号,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28106194/