有没有办法在 Internet Explorer(版本 11)(例如外部库)中使用摘要标签。
<details>
<summary>This is a summary.</summary>
<p>bla bla bla</p>
</details>
提前致谢。
最佳答案
你必须让它们自己工作,因为 IE 不支持它们。
你可以像这样检测details
/summary
:
if (typeof HTMLDetailsElement === "undefined") {
// No, not intrinsically supported
}
如果它们本质上不受支持,为了给它们设置样式,您需要告诉 IE 它们存在,您可以通过简单地创建并丢弃它们来做到这一点:
document.createElement("details");
document.createElement("summary");
然后(再次仅在本质上不支持时)为它们添加一些样式:
// JUST A ROUGH SKETCH
var style = document.createElement("style");
style.textContent =
"details > :not(summary) {\n" +
" display: none;\n" +
"}\n" +
"details.showing > :not(summary) {\n" +
" display: block;\n" +
"}\n";
document.querySelector("head").appendChild(style);
当然,并非details
中的所有元素通常都具有display: block
,因此您必须对其进行调整。 (例如,您可能对所有非 summary
内容使用 div
。)您可能还想在左侧添加箭头或类似的东西Chrome 和 Firefox 呈现这些。
通常,您会希望执行上述操作的代码位于 body
元素之前,以避免出现无样式的内容。
然后通过切换样式定义的 showing
类来响应点击 details
元素和空格/输入键:
// AGAIN: THIS IS A ROUGH SKETCH
document.addEventListener("click", detailsHandler);
document.addEventListener("keypress", detailsHandler);
function detailsHandler(e) {
if (e.type === "keypress" && [13, 32].indexOf(e.which || e.keyCode) === -1) {
return;
}
var el = e.target;
while (el && el.tagName !== "DETAILS") {
if (el.tagName === "BODY") {
el = null;
break;
}
el = el.parentNode;
}
if (el) {
el.classList.toggle("showing");
}
}
这段代码不必在body
之前,它可以在你的正常位置。但由于它在概念上是初始位的一部分,因此将其放在那里可能是有意义的。
然后确保在 details
和 summary
上都使用 tabindex="0"
以便 IE 将它们包含在 Tab 键顺序中:
<details tabindex="0">
<summary tabindex="0">This is a summary.</summary>
<p>bla bla bla</p>
</details>
实例:
<!-- In the head element -->
<script>
(function() {
if (typeof HTMLDetailsElement === "undefined") {
// Tell IE they exist
document.createElement("details");
document.createElement("summary");
document.addEventListener("click", detailsHandler);
document.addEventListener("keypress", detailsHandler);
var style = document.createElement("style");
style.textContent =
"details > :not(summary) {\n" +
" display: none;\n" +
"}\n" +
"details.showing > :not(summary) {\n" +
" display: block;\n" +
"}\n";
document.querySelector("head").appendChild(style);
}
function detailsHandler(e) {
if (e.type === "keypress" && [13, 32].indexOf(e.which || e.keyCode) === -1) {
return;
}
var el = e.target;
while (el && el.tagName !== "DETAILS") {
if (el.tagName === "BODY") {
el = null;
break;
}
el = el.parentNode;
}
if (el) {
el.classList.toggle("showing");
}
}
})();
</script>
<!-- End of in the head element -->
<!-- In body -->
<details tabindex="0">
<summary tabindex="0">This is a summary.</summary>
<p>bla bla bla</p>
</details>
关于javascript - IE 中的 HTML 摘要标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47094119/