【问题标题】:Javascript - Only works if I do an alert()Javascript - 仅当我执行 alert() 时才有效
【发布时间】:2012-07-03 21:01:09
【问题描述】:

我正在尝试在 iframe 中处理 contenteditable 正文,以防止浏览器在按 Enter 时自行添加 brpdiv。但是在尝试重置焦点时会发生一些奇怪的事情,并且它只是在处理其余代码之前发出 alert() 时才起作用。我认为这是因为javascript需要一些时间来进行操作,但是必须有一种方法可以在不“休眠”脚本的情况下进行操作...

在这里我粘贴了我的代码(使用 Jquery),只有使用“魔法警报”才能完美运行:

//PREVENT DEFAULT STUFF
var iframewindow=document.getElementById('rte').contentWindow;
var input = iframewindow.document.body;

$( input ).keypress( function ( e ) {
var sel, node, offset, text, textBefore, textAfter, range;
// the Selection object
sel = iframewindow.getSelection();
alert(sel); //MAGIC ALERT

// the node that contains the caret
node = sel.anchorNode;
alert(node); //MAGIC ALERT

// if ENTER was pressed while the caret was inside the input field
if ( node.parentNode === input && e.keyCode === 13 ) {
    // prevent the browsers from inserting <div>, <p>, or <br> on their own
    e.preventDefault();

    // the caret position inside the node
    offset = sel.anchorOffset;   

    // insert a '\n' character at that position
    text = node.textContent;
    textBefore = text.slice( 0, offset );
    textAfter = text.slice( offset ) || ' ';
    node.textContent = textBefore + '\n' + textAfter;
SEEREF=SEEREF.replace(/\n/g, "<br>");
// position the caret after that newBR character
range = iframewindow.document.createRange();
range.setStart( node, offset + 4 );
range.setEnd( node, offset + 4 );

// update the selection
sel.removeAllRanges();
sel.addRange( range );
}
});

SEEREF = framewindow.document.body.innerHTML(太长了)

编辑 当我删除 Magic Alerts 时,它仍然适用于 Chrome,但在 FF 中,它专注于一切的开始! (就像它是 offset=0 一样)

更新

似乎问题是用br 标签替换换行符的行。如果我删除此行,即使没有警报,它也能正常工作。我需要保留这个br标签,还有其他方法吗?

【问题讨论】:

  • console.log 也在做同样的事情吗?
  • 如果您忽略警报会发生什么?错误信息是什么?
  • @Mageek 我不知道这是什么...(这里我有答案,我会试试 - stackoverflow.com/questions/4743730/…)谢谢!
  • @Christoph 对不起!...我忘了说,但我的问题现在更新了。当我省略它们时,会出现任何错误消息,但它不能正常工作。
  • 我认为alert 给代码执行时间。

标签: javascript alert


【解决方案1】:

这个question 是你的一个。所以你应该结合 doc & win:

var idoc= iframe.contentDocument || iframe.contentWindow.document; // ie compatibility
var iwin= iframe.contentWindow || iframe.contentDocument.defaultView;

... idoc.getSelection() +(''+iwin.getSelection()) //firefox fix

【讨论】:

  • jmmm...谢谢,我读了两遍,但还没看懂(我现在要读慢一点)。我在哪里可以找到有关“||”的信息定义var时?它有什么作用?...我也不明白你代码的最后一行。我需要使用它来获取 iframe 选择吗?无论如何,我会再读一遍......但是你的帮助(如果可以的话)会再次很棒......非常感谢。
  • 所以.. 问题是我的代码花费了太多时间来获取 iframe 选择?
  • || 可以在 javascript 中使用,而不是在某些值为 null/未定义的情况下使用长结构 - 提供默认值。例如,如果x 为空,我们可以通过x || 5 得到 5 而不是空。因此,对于即兼容性,我们采用一个或另一个属性。关于''+iwin.getSelection() 的另一个技巧 - 意味着您将对象转换为字符串
  • 我想我知道真正的问题出在哪里......我会再次更新我的答案。对不起。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-10-18
  • 2016-01-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-02
  • 1970-01-01
相关资源
最近更新 更多