我正在研究一個簡單的文本屏幕/終端仿真器(類似於JQuery終端插件,但沒有RPC內容和窗口功能)。 屏幕的每一行都是一個表格行(一個HTML字符串),打印命令可以插入帶有一些屬性(例如前景色和背景色)的文本。每個打印的文本 都包含一個帶有樣式屬性的跨度,例如:獲取HTML字符串中封閉標籤的屬性
<span style="color:#000000;background-color:#111111">A</span><span style="color:#222222;background-color:#333333>BC</span>
這可以正常工作。現在,我想添加一個函數,該函數在給定的屏幕位置上給出了字符的所有屬性, 上面的行中,位置0(A)處的字符的顏色爲#000000。 所以我必須計算不屬於span標籤的字符並獲取最後的前面的樣式。我的第一個比較容易出錯的解決方案是:
function getAttr(line, position) {
var result = {foreground:'', background:''},
ch = '', i, j = -1, tag = false;
// Count characters
for (i = 0; i < line.length && j < position; i++) {
ch = line.charAt(i);
if (ch == '<') {
tag = true;
}
if (ch == '>') {
tag = false;
}
else if (!tag) {
j++;
}
}
i--;
// Find styles
while (i > 0 && line.charAt(i) != '<') {
if (line.substr(i, 6) == 'color:') {
result.foreground = line.substr(i + 6, 7);
}
if (line.substr(i, 17) == 'background-color:') {
result.background = line.substr(i + 17, 7);
}
i--;
}
return result;
}
有沒有計算字符(也許JQuery的或正則表達式)一個簡單的解決方案?
這與 Get parent element of a selected text 類似,但我不需要選擇,只是一個字符索引。