2009-04-25 61 views
2

參見下面的例子(無處不在的childNodes?):它顯示在一個表中的文本行(有一個很好的理由,但在這裏,這不是問題) 。在Javascript中,我可以得到標籤混亂的文本的精確座標

基本上,我需要的是一個函數,alert()是我點擊鏈接時的文本選擇的完美座標。通過完美的座標,我的意思是:選擇開始的行號,選擇結束的行數(這兩個是微不足道式的,我只是用數在<td> ID,選擇的開始偏移,選擇的端部的偏移

所以,如果我選擇

第一線,它包含文本
這是第二

我得到的是說一個警告:

選擇開始於1號線,偏移12
選擇在第2行結束,偏移18

這將是與getRange(很容易)(我不需要這麼getRange Internet Explorer的兼容性()的如果文本是純文本的,則可以使用FireFox,Chrome和Safari)。這裏的問題是<span>, <strong> and <em>標籤無處不在,並且它們中的每一個都是新的childNode。所以getRange()不起作用。

我還沒有找到一種方法來忽略標記。看來有沒有簡單的方法來做到這一點。但我不是JavaScript專家,也許有一種技巧可以忽略文本中的標籤(或使其功能像忽略)。

<a href="javacript: magicCode();">Select some text in the table then click here</a>
<table>
<tr>
<td id="content1">This <span class="one">is the</span> first line <span class="two">and it contains</span> text</td>
</tr>
<tr>
<td id="content2">This is the <span class="three">second line and it contains text</span></td>
</tr>
<tr>
<td id="content3"><span class="four">This is <span class="five">the third</span> line and it</span> contains text</td>
</tr>
<tr>
<td id="content4">This is <strong>the fourth <em>line</em> and it</strong> contains text</td>
</tr>
<tr>
<td id="content5">This is the fifth line and it contains text</td>
</tr>
</table>

誰能幫我寫我的magicCode()?

謝謝!

回答

1

您可以使用.textContent屬性來獲取沒有HTML的文本值。通過檢查.innerText並使用它,如果它存在,您可以很容易地使其在所有瀏覽器中工作,否則使用.textContentinnerText作品在IE和textContent作品在Firefox/Chrome瀏覽器等

這裏有一個例子:

var content = document.getElementById('content1'); 
if(content.innerText){ 
    alert(content.innerText); 
}else{ 
    alert(content.textContent); 
} 
0

你可能要考慮使用canvas標籤來生成文本;它可能有點複雜,並且對於你的項目來說是頂級的。

Bespin是一個完全用canvas標籤創建的代碼編輯器。我沒有看到源代碼,所以我不能告訴你他們如何設法呈現文本和模仿文本選擇。

https://bespin.mozilla.com/