这是一个非常有趣的问题;谢谢!以下是添加html2style()
和style2html()
方法的脚本。测试用例表明您可以在两者之间进行转换,而不会发生视觉变化(尽管元素嵌套的顺序在往返之后可能会有所不同)。
显示这些工作的测试用例
http://jsfiddle.net/GaPBS/
将嵌套的 HTML 短语元素转换为样式属性
(function(scope){
var HTML2CSS = {
strong: function(e){ this.style.fontWeight = "bold"; },
b: function(e){ this.style.fontWeight = "bold"; },
em: function(e){ this.style.fontStyle = "italic"; },
i: function(e){ this.style.fontStyle = "italic"; },
font: function(e){ this.style.fontFamily = e.getAttribute('face'); },
u: function(e){ this.style.textDecoration += ' underline'; },
strike: function(e){ this.style.textDecoration += ' line-through'; }
};
scope.html2style = function(root){
for (var name in HTML2CSS){
var elements = root.querySelectorAll(name);
var styler = HTML2CSS[name];
for (var i=elements.length;i--;){
var toKill = elements[i],
parent = toKill.parentNode;
// Only swap out nodes that are the sole element child of the parent
if (!toKill.nextElementSibling && !toKill.previousElementSibling){
parent.removeChild(toKill);
// Move contents into the parent
for (var kids=toKill.childNodes,j=kids.length;j--;){
parent.insertBefore(kids[j],parent.firstChild);
}
// Merge existing styles from this node onto the parent
parent.style.cssText += toKill.style.cssText;
// Hard set the style for this node onto the parent
styler.call(parent,toKill);
}
}
}
}
})(this);
将样式属性转换为嵌套的 HTML 短语元素
(function(scope){
var CSS2HTML = {
"fontWeight:bold": "b",
"fontStyle:italic": "i",
"textDecoration:underline": "u",
"textDecoration:line-through": "strike",
"font-family:*": function(value){ var e=document.createElement('font'); e.setAttribute('face',value); return e; }
};
scope.style2html = function(root){
var leaf = root;
for (var style in CSS2HTML){
var elName = CSS2HTML[style],
parts = style.split(':'),
name = parts[0],
wild = parts[1]=="*",
regex = !wild && new RegExp("(^|\\s)"+parts[1]+"(\\s|$)"),
before = root.style[name];
if (before && (wild || regex.test(before))){
var el = (typeof elName==='function') ? elName(before) : document.createElement(elName);
for (var kids=leaf.childNodes,j=kids.length;j--;){
el.insertBefore(kids[j],el.firstChild);
}
leaf = leaf.appendChild(el);
root.style[name]=wild ? "" : before.replace(regex,"");
}
}
if (root.getAttribute('style')=="") root.removeAttribute('style');
}
})(this);