如何将光标移动到所见即所得框的末尾并设置焦点

How to move cursor to the end of WYMeditor box and set focus?

本文关键字:焦点 设置 所见即所得 光标 移动      更新时间:2023-09-26

我在论坛上使用WYMEditor,用户可以"引用"他人的消息。在这种情况下,WYMEditor加载的内容被封装在blockquote标记中。

不幸的是,报价的内容通常比输入框的大小占用更多的空间,当用户点击框时,最终会在块报价中输入他们的文本。这会导致混乱的消息。

我想要的是将所见即所得编辑器的内容滚动到底部,将光标放在最后,并将焦点放在wym框上。不幸的是,WYMEditorapi中没有这样的功能。有一些未记录的函数在源代码中提供选择管理,但我的JavaScript/jQuery技能不足以利用它们——我尝试过,但失败了。

postInit选项和jQuery scrollTop函数的组合应该可以完成任务。我还建议为它们插入一个占位符段落,同时滚动到底部。例如:

jQuery('.wymeditor').wymeditor({
    postInit: function (wym) {
        var $contents,
            $p,
            $blockquote = jQuery(wym._doc).find('blockquote');
        // Insert a placeholder empty paragraph 
        // so that users will be encouraged to not type inside the blockquote
        $blockquote.after("<p>");
        // Scroll the iframe to the bottom
        $contents = $(wym._iframe).contents();
        $contents.scrollTop($contents.height());
        // Move the selection to the paragraph
        $(wym._iframe).focus();
        $p = jQuery(wym._doc).find('p');
        var sel = rangy.getIframeSelection(wym._iframe),
            range = rangy.createRange(wym._doc);
        range.setStart($p[0], 0);
        range.setEnd($p[0], 0);
        range.collapse(true);
        sel.setSingleRange(range);
        if (jQuery.browser.msie) {
            wym.saveCaret();
        }    
    }
});