opt*_*sta 14 javascript text editor font-size contenteditable
我正在使用Rich Text Editor进行Web浏览器,我想在RTE/ContentEditable元素中使用当前字体颜色和大小的值.是否有一些预先选择的函数来获取这些值,例如execCommand,它直接与ContentEditable元素连接?或者我应该使用一些文本范围的jQuery库来获取这些属性?
Tim*_*own 30
您可以使用它document.queryCommandValue()来获取所有主流浏览器中当前选择的颜色和字体大小:
现场演示:http://jsfiddle.net/timdown/AJBsY/
码:
var colour = document.queryCommandValue("ForeColor");
var fontSize = document.queryCommandValue("FontSize");
Run Code Online (Sandbox Code Playgroud)
但是,结果在浏览器中不一致,并且该FontSize命令仅适用于HTML <font>元素中使用的字体大小1-7 而不是CSS,因此您最好抓住包含选择的元素并使用window.getComputedStyle()/ 检查其CSS属性.currentStyle:
现场演示:http://jsfiddle.net/timdown/K4n2j/
码:
function getComputedStyleProperty(el, propName) {
if (window.getComputedStyle) {
return window.getComputedStyle(el, null)[propName];
} else if (el.currentStyle) {
return el.currentStyle[propName];
}
}
function reportColourAndFontSize() {
var containerEl, sel;
if (window.getSelection) {
sel = window.getSelection();
if (sel.rangeCount) {
containerEl = sel.getRangeAt(0).commonAncestorContainer;
// Make sure we have an element rather than a text node
if (containerEl.nodeType == 3) {
containerEl = containerEl.parentNode;
}
}
} else if ( (sel = document.selection) && sel.type != "Control") {
containerEl = sel.createRange().parentElement();
}
if (containerEl) {
var fontSize = getComputedStyleProperty(containerEl, "fontSize");
var colour = getComputedStyleProperty(containerEl, "color");
alert("Colour: " + colour + ", font size: " + fontSize);
}
}
Run Code Online (Sandbox Code Playgroud)
这是一种改进,但仍然存在浏览器不一致,例如不同的单位或颜色格式.
| 归档时间: |
|
| 查看次数: |
8561 次 |
| 最近记录: |