HTML的<details>标签在IE/Edge中不起作用。

10

我想添加一个可以展示和隐藏的附加可切换部分。

我的要求:

  • 支持主流浏览器(Opera,Chrome,Edge,IE11,Firefox,Mac上的Safari)
  • 无需JavaScript

我正在考虑使用<details>标签,但代码

<details>
  <summary>Toggle</summary>
  <p>Hideable</p>
</details>

在Edge / IE浏览器上无法正常工作。

我是否可以以某种方式“让”它工作,或者是否有其他东西可以用来完成这项任务?如果没有JavaScript存在,则黑客是可以接受的。


2
如果添加必要的附加元素(前者为链接,后者为复选框+标签)不是问题,那么:target:checked都可以使用。https://www.sitepoint.com/css3-vertical-accordion-using-target-selector/和http://geoffgraham.me/css-only-accordion-using-the-checkbox-hack/解释了这两种技术背后的基本原则。 - CBroe
@CBroe 太酷了,我想不到。我猜你应该把它发布为一个答案。 - wscourge
3个回答

14

您可以在页面上添加一个polyfill,使页面上的所有<details/>都能工作:

<!-- Inside the body -->
<script src="//cdn.jsdelivr.net/npm/details-polyfill@1/index.min.js" async></script>

我知道这是一个JS解决方案,但它不需要为每个单独的<details/>编写任何JS。 它可以与在所见即所得编辑器中编写的文本一起使用。


您可能还需要更新ARIA-expanded以使其与辅助工具配合使用,并添加tabindex=0以使其与键盘导航配合使用。 - barefootliam
@barefootliam,请将其发送至https://github.com/rstacruz/details-polyfill/issues/new。 - Finesse
完成。以下是有关该主题的一篇文章链接,可能会有所帮助。 - barefootliam

7
这是建议使用隐藏复选框的:checked方法:

.toggler {
  display: none;
}

.toggler+.toggler-content {
  max-height: 0;
  opacity: 0;
  overflow: hidden;
  transition: all .4s ease-in-out;
}

.toggler:checked+.toggler-content {
  max-height: 1000px;
  opacity: 1;
}
<div>
  <label for="toggler-id-1">Toggle</label>
  <input type="checkbox" id="toggler-id-1" class="toggler" />
  <div class="toggler-content">Hideable</div>
</div>

我仍然更倾向于使用@Finesse的解决方案,因为它允许你使用符合语义的HTML元素来实现目的。


-3

复制下面的脚本,将其放入js文件中,然后导入它或直接在标签中编写。这对我有用。

!function(e,t){"function"==typeof define&&define.amd?define(t):"object"==typeof exports?module.exports=t():t()}(0,function(){var o="details",i="summary";(function(){var e=document.createElement(o);if(!("open"in e))return!1;e.innerHTML="<"+i+">a</"+i+">b",document.body.appendChild(e);var t=e.offsetHeight;e.open=!0;var n=t!=e.offsetHeight;return document.body.removeChild(e),n})()||(document.documentElement.className+=" no-details",window.addEventListener("click",function(e){if("summary"===e.target.nodeName.toLowerCase()){var t=e.target.parentNode;if(!t)return;t.getAttribute("open")?(t.open=!1,t.removeAttribute("open")):(t.open=!0,t.setAttribute("open","open"))}}),function(e,t){if(document.getElementById(e))return;var n=document.createElement("style");n.id=e,n.innerHTML=t,document.getElementsByTagName("head")[0].appendChild(n)}("details-polyfill-style","html.no-details "+o+":not([open]) > :not("+i+") { display: none; }\nhtml.no-details "+o+" > "+i+':before { content: "▶"; display: inline-block; font-size: .8em; width: 1.5em; }\nhtml.no-details '+o+"[open] > "+i+':before { content: "▼"; }'))});

如果你不想要那些箭头,那么就从结尾删除这一部分

+o+" > "+i+':before { content: "▶"; display: inline-block; font-size: .8em; width: 1.5em; }\nhtml.no-details '+o+"[open] > "+i+':before { content: "▼"; }'


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接