DIV CSS 佈局教程網

用 JavaScript 清理 table 樣式
編輯:關於JavaScript     

專案中遇到這樣的需求:一大段文章正文的 HTML 在手機上顯示不全,原因是其中的 table,而表格的 tr/td 都帶有從 Word 貼上來的樣式。需要把這段字串中 table、tr、td 上的樣式清除掉,同時又不能破壞表格結構,也就是要保留 tr 的 rowspan 與 td 的 colspan 屬性。

HTML 部分程式碼如下:

 <table>
 <tbody>
 <tr style="height:13.5pt">
 <td width="117" style="width:88.0pt;border:solid windowtext 1.0pt;">項目</td>
 <td width="137" style="width:103.0pt;border:solid windowtext 1.0pt;">金額</td>
 </tr>
 <tr style="height:13.5pt">
 <td width="117" style="width:88.0pt;border:solid windowtext 1.0pt;">合計</td>
 <td colspan="3" valign="bottom" style="width:103.0pt;"></td>
 </tr>
 </tbody>
 </table>

JS 腳本如下:

 /*
 * 格式化內容,str 即是 html 格式的字串
 */
 function formatContent(str) {
 str = str.replace(/<\/?(html|head|title|meta|body)\b[^>]*>/ig, "");
 str = str.replace(/<table[^>]*>/ig, "<table>");
 str = str.replace(/(<tr[^>]*>)/ig, function (a, b) {
 if (a.indexOf('rowspan') > -1) {
 a = a.replace(/([a-z]+)="([^"]+)"?/ig, function (c, d, e) {
 return d === 'rowspan' ? (d + '="' + e + '"') : '';
 })
 return a;
 } else {
 return '<tr>';
 }
 });
 str = str.replace(/(<td[^>]*>)/ig, function (a, b) {
 if (a.indexOf('colspan') > -1) {
 a = a.replace(/([a-z]+)="([^"]+)"?/ig, function (c, d, e) {
 return d === 'colspan' ? (d + '="' + e + '"') : '';
 })
 return a;
 } else {
 return '<td>';
 }
 });
 return str;
 }

這個函式的作法是:先清掉多餘的 html、head、body 等標籤,再把 table 標籤正規化,然後針對 tr 與 td,若含 rowspan/colspan 就只保留該屬性,否則還原成乾淨的 <tr> 或 <td>,如此便能清除 Word 帶入的樣式,同時保留合併儲存格所需的屬性。以上就是本文的完整內容,希望對大家有所幫助。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved