在JavaFX HTMLEditor中定位插入符号

时间:2015-01-23 08:57:02

标签: javascript javafx

之前没有做过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中?

1 个答案:

答案 0 :(得分:0)

好吧,我终于开始工作了。我不确定为什么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();
        }
    }