YUI编辑器(RTE):如何使用< span>并不会丢失格式? [英] YUI editor (RTE): How to wrap selection with a <span> and NOT lose formatting?
问题描述
好的,所以我遇到了上个星期左右一直在研究的问题,并尝试了我所知道或可以找到的一切.我正在使用YUI 2.x编辑器,用户将在其中进行大量格式化.我在页面上有一个外部按钮,当用户单击该按钮时,需要将选择的文本包装在<span>
中,但是必须做到这一点而不会失去任何格式.由于某些原因,执行以下操作会删除所选内容中的所有格式:
Ok so I've got a problem I've been working on for the last week or so and have tried everything I know or could find. I am using YUI 2.x editor where users will be doing some heavy formatting. I have an external button on the page that needs to wrap the selected text in a <span>
when the user clicks it, but it must do this without loosing any formatting. For some reason doing the following likes to erase all of the formatting in the selection:
var sel = myEditor._getSelection();
var newEl = '<span>' + sel + '</span>';
myEditor.execCommand('inserthtml', newEl);
所以要解决这个问题,我认为最好的方法是将_getSelectedElement()
和_createCurrentElement('span')
一起使用,以重新添加样式元素.这是到目前为止我得到的:
So to solve this, I think the best way is to use _getSelectedElement()
along with _createCurrentElement('span')
to add back the style elements. Here's what I've got so far:
function createSpan() {
var el = myEditor._getSelectedElement();
var sel = myEditor._getSelection();
// IE support
if (document.selection) {
sel = myEditor._getDoc().selection.createRange();
newText = sel.text;
}
else {
newText = sel;
}
// Create the new element with the old styles
myEditor._createCurrentElement('span', {color: el.style.color, fontSize: el.style.fontSize, fontFamily: el.style.fontFamily});
myEditor._selectNode(myEditor.currentElement[0]);
myEditor.currentElement[0].innerHTML = newText;
return myEditor.currentElement[0];
}
如果_getSelectedElement()
正确返回具有正确样式的元素,此方法效果很好,但是我发现如果用户选择整个段落,它将返回BODY
.而且由于BODY
没有任何样式,因此它们又迷路了.
This works great if _getSelectedElement()
properly returns the element with the correct styles, but I have found that if a user selects an entire paragraph, it will return the BODY
. And since the BODY
doesn't have any styles, they again get lost.
基本上,我需要它的行为类似于工具栏上的加粗"按钮,但使用的是<span>
而不是<b>
.为什么这么难?
Basically, I need it to behave like the Bold button on the toolbar but use a <span>
and not <b>
. Why is this so hard?
有什么想法或建议吗?谢谢!
Any ideas or suggestions? Thanks!
推荐答案
原来要做的就是:
myEditor._createCurrentElement('span');
newEl = myEditor.currentElement[0];
_createCurrentElement
在内部创建一个新元素,并将当前选择内容作为innerHTML,并为您保留格式.如此简单...感谢Dav Glass的帮助.
在这里查看他的帖子: http://yuilibrary .com/forum/viewtopic.php?f = 89& t = 5436& p = 18659#p18659
_createCurrentElement
internally creates a new element with the current selection as the innerHTML and preserves the formatting for you. So simple...thanks to Dav Glass for his help.
Check out his post here: http://yuilibrary.com/forum/viewtopic.php?f=89&t=5436&p=18659#p18659
这篇关于YUI编辑器(RTE):如何使用< span>并不会丢失格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!