function htmlIsWhitespace(input) {
\t var visible = [
\t \t \t 'img','iframe','object','hr',
\t \t \t 'audio', 'video',
\t \t \t 'form', 'button', 'input', 'select', 'textarea'
\t \t ],
\t \t container = document.createElement('div');
\t container.innerHTML = input;
\t return !(container.innerText.trim().length > 0 || container.querySelector(visible.join(',')));
}
// And the tests (I believe these are comprehensive):
var testStringsYes = [
\t \t "",
\t \t "<a href='#'></a>",
\t \t "<a href='#'><span></span></a>",
\t \t "<a href='#'><span> <!-- comment --></span></a>",
\t \t "<a href='#'><span> </span></a>",
\t \t "<a href='#'><span> </span></a>",
\t \t "<a href='#'><span> </span></a> ",
\t \t "<p><a href='#'><span> </span></a> </p>",
\t \t " <p><a href='#'><span> </span></a> </p> <p></p>",
\t \t "<p>\n \n</p><ul><li></li></ul>"
\t ],
\t testStringsNo = [
\t \t "<a href='#'><span> hi</span></a>",
\t \t "<img src='#foo'>",
\t \t "<hr />",
\t \t "<div><object /></div>",
\t \t "<div><iframe /></div>",
\t \t "<div><object /></div>",
\t \t "<div><!-- hi -->bye</div>",
\t \t "<div><!-- what --><audio></audio></div>",
\t \t "<div><!-- what --><video></video></div>",
\t \t '<form><!-- empty --></form>',
\t \t '<input type="text">',
\t \t '<select name="foo"><option>1</option></select>',
\t \t '<textarea>',
\t \t '<input type="text">',
\t \t '<form><input type="button"></form>',
\t \t '<button />',
\t \t '<button>Push</button>',
\t \t "yo"
\t ];
for(var yy=0, yl=testStringsYes.length; yy < yl; yy += 1) {
\t console.debug("Testing", testStringsYes[yy]);
\t console.assert(htmlIsWhitespace(testStringsYes[yy]));
}
for(var nn=0, nl=testStringsNo.length; nn < nl; nn += 1) {
\t console.debug("Testing", testStringsNo[nn]);
\t console.assert(!htmlIsWhitespace(testStringsNo[nn]));
}
您可以使用CSS來呈現內容的頁面,只是在看標記可能不足以 – Musa
使用DOM API,你有沒有考慮空白字符的列表,遞歸確認是否任何給定節點的唯一內容是空白文本(或節點是註釋等),如果是,則刪除該節點;如果您沒有節點,則全部爲空格。 - 請注意,這不會在白色背景上捕捉白色文字,例如... – deceze