【问题标题】:How to format contenteditable div as you type?如何在键入时格式化 contenteditable div?
【发布时间】:2011-05-02 06:29:56
【问题描述】:

我正在尝试编写一个函数,该函数允许内容可编辑的 div 在用户输入 div 时进行一些自动格式化。到目前为止,我只设法使它在 IE 中工作。谁能帮帮我?

function formatOnKeyUp(){
    if (window.getSelection) {
        // ???????
    } else if (document.selection) {
        cursorPos=document.selection.createRange().duplicate();
        clickx = cursorPos.getBoundingClientRect().left; 
        clicky = cursorPos.getBoundingClientRect().top;
    }

    text = document.getElementById('div1').innerHTML;
    text = text.replace(/this/gm, "<i>this</i>");
    // .... some other formating here...
    document.getElementById('div1').innerHTML = text;

    if (window.getSelection) {
        // ????????
    } else if (document.selection) {
        cursorPos = document.body.createTextRange();
        cursorPos.moveToPoint(clickx, clicky);
        cursorPos.select();
    }
}

【问题讨论】:

  • 为什么不使用现成的编辑器,让您可以根据自己的喜好设置文本格式?查看tinymce.moxiecode.com
  • 我需要它自动格式化为用户类型,而不是用户点击某个按钮。此外,这是整个应用程序的一部分。第三方所见即所得编辑器不是我所追求的。

标签: javascript html contenteditable


【解决方案1】:

您可以在我的Rangy 库中使用selection save and restore module,它在选择边界处使用不可见的标记元素。我还建议在 keboard 不活动一段时间后进行更换,而不是在每次 keyup 事件时进行更换:

function formatText(el) {
    // Save the selection
    var savedSel = rangy.saveSelection();

    // Do your formatting here
    var text = el.innerHTML.replace(/this/gm, "<i>this</i>");
    el.innerHTML = text;

    // Restore the original selection 
    rangy.restoreSelection(savedSel);
}

var keyTimer = null, keyDelay = 500;

document.getElementById('div1').onkeyup = function() {
    if (keyTimer) {
        window.clearTimeout(keyTimer);
    }
    keyTimer = window.setTimeout(function() {
        keyTimer = null;
        formatText(document.getElementById('div1'));
    }, keyDelay);
};

【讨论】:

  • @Marcel:谢谢 :) 现在只需要完成记录和测试这个愚蠢的东西。
  • 嗨,蒂姆,我怀疑 Firefox 版本中存在一些错误。有什么渠道可以将我的发现反馈给你吗?
  • 好的,我希望这会有所帮助。在 Firefox 中,脚本无法呈现以下情况:这是 一些 区域类型。
  • 请注意,您的专有 span 标签就在 标签之后。 也会出现类似的问题。错误消息是“索引或大小为负数或大于允许的数量”代码:“1 [Break on this error] var endNode = ec.childNodes[eo - 1];”
  • @Kelly:理想的情况是在项目错误跟踪器上提交错误:code.google.com/p/rangy/issues/list。我会尽快看看。
【解决方案2】:

光标位置和文本范围的东西看起来是微软 JScript 特有的。

如果您在某人键入时替换文本,为什么需要该代码?

【讨论】:

  • 因为我需要格式化输入的文本。我正在编写类似 html 编辑器的东西。当有人输入时,比如说 ,我希望在用户完成输入 <title> 的那一刻它是不同的颜色。
猜你喜欢
  • 1970-01-01
  • 2022-01-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-25
  • 2013-04-20
  • 2014-03-28
相关资源
最近更新 更多