4

我正在为 IE 开发富文本编辑器,我想问一个关于在当前插入点获取“fontname”值的问题。

问题在于空行,假设在用户输入的编辑器中:

line 1

line 2

空行位于“line 1”和“line 2”之间,本例中空行的html源代码为(由IE在用户按“enter”时生成):

<P><FONT size=5 face="Courier New"></FONT>&nbsp;</P>

问题是这样的:document.queryCommandValue("fontname")在鼠标单击空行和使用键盘将光标移动到空行的情况下给我不同的值。

在鼠标点击的情况下,它给了我浏览器的默认字体名称,而在另一种情况下(使用键盘移动光标)它给了我正确的字体名称(“Courier New”)。

实际上在这两种情况下,document.selection具有不同的“类型”值:鼠标单击时的“文本”和键盘时的“无”。

任何帮助都感激不尽!

如果我的问题不清楚,请告诉我。

4

1 回答 1

2

有点不清楚您要达到的目标。但是,您似乎正在尝试从没有字体的区域获取字体。不间断空格 ( &nbsp;) 在字体标签 ( <FONT> . . . </FONT>) 之外,因此没有该标签的任何属性(面或大小)。如果非中断空间在字体标签内,你可以得到它的脸。

这是一个说明这一点的小提琴。为了看到一些东西,我&nbspHello.

HTML:

<!-- Hello is outside the font tag. -->
<P><FONT size=5 face="Courier New"></FONT>Hello</P>

<!-- Hello is inside the font tag. -->
<p><font size=5 face="Times New Roman">Hello</font><p>

Javascript:

// Alert the face
function handleFonts(e) {
    alert(this.face);
}

// Get all the font elements
var el = document.querySelectorAll("font");

// Bind event handlers to the elements
// The last element of "el" is it's length so we only
// iterate to el.length - 1 or i < el.length
for (var i = 0; i < el.length; i++) {
    el[i].addEventListener("click", handleFonts, true);
    el[i].addEventListener("keypress", handleFonts, true);
}

单击第一段标签中的文本不会触发任何内容。单击第二个中的文本可以正常工作。

我们可以通过一些额外的 javascript 来解决这个问题。

使用第一个标签中的 HTML 和下面的 Javascript,我们可以在包含 的标签内获取字体的外观&nbsp,即使&nbsp不在该字体标签内。

HTML:

<p id="last-p-tag"><font size=5 face="Tahoma"></font>Hello</p>

Javascript:

// Get the paragraph tag we want
var lastPTag = document.getElementById("last-p-tag");

// Bind an event to clicking on it
lastPTag.addEventListener("click", function(e) {
    // Alert the face attribute of the first font element
    // within that p tag
    alert(this.querySelector("font").face);
}, true);

这包含在小提琴的末尾。

于 2013-10-20T15:43:53.240 回答