Javascript - 仅当我执行警报()时才有效
Javascript - Only works if I do an alert()
我正在尝试处理iframe中的内容可编辑正文,以防止浏览器在按Enter键时自行添加br
,p
或div
。但是在尝试重置焦点时会发生一些奇怪的事情,并且在处理其余代码之前发出 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 (它太长了)
编辑当我删除魔术警报时,它仍然可以在 Chrome 上运行,但在 FF 中,它专注于一切的开始!(就像偏移量=0)
更新
似乎问题是用br
标签替换换行符的行。如果我删除此行,即使没有警报,它也能完美运行。我需要保留这个br
标签,还有其他方法吗?
这个问题很
狭隘。所以你应该结合doc & win:
var idoc= iframe.contentDocument || iframe.contentWindow.document; // ie compatibility
var iwin= iframe.contentWindow || iframe.contentDocument.defaultView;
... idoc.getSelection() +(''+iwin.getSelection()) //firefox fix
相关文章:
- 无法在通过jQuery的ajax加载的页面中执行javascript
- JavaScript执行暂时挂起页面
- 如何在ReactJS JSX中执行嵌套的if-else语句
- 为什么自我执行匿名有效
- 外部链接的Javascript文件赢得't执行,但函数有效
- Object.defineProperty()在测试(jpm运行)过程中有效,但不起作用;使用实际xpi时,不要执行任何
- 有没有更有效的方法在 JavaScript 中执行二进制插入排序
- MVC $.ajax 调用从不对编辑执行控制器操作,但在添加时有效
- Javascript - 仅当我执行警报()时才有效
- JS验证在正常速度下失败,但在单步执行代码时有效
- 有没有一种有效的方法来执行不区分大小写的 JavaScript 对象属性名称查找
- 在 JavaScript 中按特定键执行某些操作在 Chrome 中有效,但在 Firefox 中不起作用
- eval_in_page javascript执行在firefox中有效,但在phantomjs中无效
- 只有当我执行alert()时,Javascript循环才有效
- 在jQuery中执行此过程的最有效方法是什么?
- 如何有效地限制在鼠标悬停事件中执行的AJAX请求
- 使用jQuery基于匹配表单输入值执行操作的最有效方法是什么?
- 多个元素的jQuery没有执行,尽管在概念上有效
- 此策略中不应执行具有有效分页cookie的CRM 2011查询
- 为什么这个函数有效?不应该在每次调用函数时“执行”都返回 false