问题描述
我在使用使用createLink"命令的所见即所得编辑器时尝试添加属性.我认为在浏览执行该命令后取回创建的节点是微不足道的.
I am trying to add an attribute when using a wysiwyg editor that uses "createLink" command. I thought it would be trivial to get back the node that is created after the browse executes that command.
事实证明,我只能在 IE 中获取这个新创建的节点.有什么想法吗?
Turns out, I am only able to grab this newly created node in IE. Any ideas?
以下代码演示了该问题(底部的调试日志在每个浏览器中显示不同的输出):
The following code demonstrates the issue (debug logs at bottom show different output in each browser):
var getSelectedHTML = function() {
if ($.browser.msie) {
return this.getRange().htmlText;
} else {
var elem = this.getRange().cloneContents();
return $("<p/>").append($(elem)).html();
}
};
var getSelection = function() {
if ($.browser.msie) {
return this.editor.selection;
} else {
return this.iframe[0].contentDocument.defaultView.getSelection();
}
};
var getRange = function() {
var s = this.getSelection();
return (s.getRangeAt) ? s.getRangeAt(0) : s.createRange();
};
var getSelectedNode = function() {
var range = this.getRange();
var parent = range.commonAncestorContainer ? range.commonAncestorContainer :
range.parentElement ? range.parentElement():
range.item(0);
return parent;
};
// **** INSIDE SOME EVENT HANDLER ****
if ($.browser.msie) {
this.ec("createLink", true);
} else {
this.ec("createLink", false, prompt("Link URL:", "http://"));
}
var linkNode = $(this.getSelectedNode());
linkNode.attr("rel", "external");
$.log(linkNode.get(0).tagName);
// Gecko: "body"
// IE: "a"
// Webkit: "undefined"
$.log(this.getSelectedHTML());
// Gecko: "<a href="http://site.com">foo</a>"
// IE: "<A href="http://site.com" rel=external>foo</A>"
// Webkit: "foo"
$.log(this.getSelection());
// Gecko: "foo"
// IE: [object Selection]
// Webkit: "foo"
感谢您对此的任何帮助,我已经搜索了有关 SO 的相关问题,但没有成功!
Thanks for any help on this, I've scoured related questions on SO with no success!
推荐答案
这是我用来获取文本光标的parentNode"的代码:
This is the code I've used to get the "parentNode" of the text cursor:
var getSelectedNode = function() {
var node,selection;
if (window.getSelection) {
selection = getSelection();
node = selection.anchorNode;
}
if (!node && document.selection) {
selection = document.selection
var range = selection.getRangeAt ? selection.getRangeAt(0) : selection.createRange();
node = range.commonAncestorContainer ? range.commonAncestorContainer :
range.parentElement ? range.parentElement() : range.item(0);
}
if (node) {
return (node.nodeName == "#text" ? node.parentNode : node);
}
};
我调整了我的 IE 方法来接近你的方法.经测试可在 IE8、FF3.6、Safari4、Chrome5 上运行.我设置了一个 jsbin 预览,你可以用它来测试.
I tweaked my IE method to approximate yours. Tested and working IE8, FF3.6, Safari4, Chrome5. I set up a jsbin preview that you can test with.
这篇关于从 Gecko 和 Webkit 中的选择(范围)中检索父节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!