简体   繁体   English

GWT在内容可编辑div上设置插入符位置

[英]GWT set caret position on content editable div

I'm writing a web based code editor, where every line is a content editable div. 我正在编写一个基于Web的代码编辑器,其中每一行都是一个内容可编辑的div。 I wrote a native method to set caret position on a given index, but it works only in chrome. 我写了一个本机方法来设置给定索引上的插入符号位置,但它仅在chrome中有效。 opera and firefox always sets caret on a beggining of a line. 歌剧和Firefox总是在行的开头设置插入符号。

public native void setCursorPos(int index) /*-{
    //console.log(index);
    var that = this.@edu.pg.client.CodeLine::getElement()();
    var position = index;
    var el = that;
    var treeWalker = document.createTreeWalker(el, NodeFilter.SHOW_TEXT,
            function(el) {
                return NodeFilter.FILTER_ACCEPT;
            }, false);

    while (treeWalker.nextNode()) {
        if (position - treeWalker.currentNode.length <= 0) {
            var range = document.createRange();
            var sel = window.getSelection();
            console.log(position);
            range.setStart(treeWalker.currentNode, position);
            range.setEnd(treeWalker.currentNode, position);
            range.collapse(true);
            sel.removeAllRanges();
            sel.addRange(range);
            el.focus();
            return;
        } else {
            position = position - treeWalker.currentNode.length;
        }
    }

while testing a code i was using this http://jsbin.com/EcETajo/5/edit and it works in chrome, ff and opera. 在测试代​​码时,我使用的是http://jsbin.com/EcETajo/5/edit ,它可以在chrome,ff和Opera中运行。

is the function wrong or something on the gwt generated code changes caret position ? 是函数错误还是gwt生成的代码上的某些内容更改了插入符号的位置?

EDIT: im using treewalker because i want to handle text hightlighting by wrapping text in span nodes in future 编辑:我正在使用treewalker,因为我想通过将来在span节点中包装文本来处理文本高亮显示

EDIT2: ok, ive found a problem by myself. EDIT2:好的,我自己发现一个问题。

var range = document.createRange(); var range = document.createRange(); var sel = window.getSelection(); var sel = window.getSelection();

those lines were wrong. 这些行是错误的。 js code in gwt is in iframe, so to access my html elements i had to use something like this var range = $doc.createRange(); gwt中的js代码在iframe中,因此要访问我的html元素,我必须使用类似var range = $ doc.createRange();之类的东西。 var sel = $doc.getSelection(); var sel = $ doc.getSelection(); wher $doc is a variable set by gwt $ doc是gwt设置的变量

在gwt本机方法中正确使用文档和窗口对象是通过使用gwt框架设置的$ wnd和$ doc

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM