<details> 用快捷方式一一打开

问题描述

我尝试在按“a”键按顺序打开时进行设置,但它同时打开。

预期结果:

  1. “a”键 = 打开详细信息1
  2. “a”键 = 打开详细信息2
  3. “a”键 = 打开详细信息3

document.onkeyup = function(e) {
    var e = e || window.event;
    if (e.which == 65) {
        $('details').attr('open',true);
    }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<details>
    <summary>Details1</summary>
    test1
    
    <details>
        <summary>Details2</summary>
    test2
    
        <details>
            <summary>Details3</summary>
    test3

        </details>
    </details>
</details>

解决方法

这边

const details_tree = [...document.querySelectorAll('body>details,body>details>details,body>details>details>details')]

document.onkeydown=e=>
  {
  if (e.key==='a')                   // open
  for (let D of details_tree) 
  if (!D.open) 
    {
    D.open = true
    break
    }
  if (e.key==='b')                    // close
  for (let i=details_tree.length;i--;) 
  if (details_tree[i].open) 
    {
    details_tree[i].open = false
    break
    }
  } 
details {
  margin  : .5em;
  border  : 1px solid lightgrey;
  padding : .4em;
}
<details>
  <summary>Details1</summary>
  test1
  <details>
    <summary>Details2</summary>
    test2
    <details>
      <summary>Details3</summary>
      test3
    </details>
  </details>
</details>

,

JQuery 返回与查询匹配的元素集合,并在集合上调用方法对每个成员执行该方法 - 这是它们同时打开的原因。

  • 要一次打开 details 一个,您可以遍历集合并打开第一个未打开的集合。
  • 要关闭最后一个打开的元素,您可以从 details 集合中创建一个数组,反转该数组,从该数组中创建一个新集合,在反转集合中找到第一个打开的元素并关闭它(呼)。
  • 要关闭所有打开的元素,只需从整个 open 集合中删除 details 属性。

请注意,open 是一个没有值的属性 - 如果该属性存在,则 details 元素处于打开状态,如果不存在则关闭。

不幸的是,jQuery 没有“hasAttribute”函数,虽然已经设计了变通方法,但其中许多不适用于没有值的属性。然而,原生的 hasAttribute 元素方法比 <details> 元素存在的时间更长,并且在所有现代浏览器中都受支持。

因此,使用 jQuery(主要是)您可以尝试以下操作。输入 'a' 打开单个元素,输入 'c' 关闭最后一个打开的元素,或输入 'z' 关闭所有打开的(详细信息)元素:

document.onkeyup = function(e) {
    var e = e || window.event;
    if (e.which == 65) {        // 'a' - open one
        $('details').each( function() {
            if( this.hasAttribute("open")) {
                return true;
            }
            $(this).attr("open",true);
            return false;   
        });
    }
    else if(e.which == 67) {    // 'c' - close one
       $($('details').get().reverse()).each( function() {
            if( this.hasAttribute("open")) {
                $(this).removeAttr("open");
                return false;
            }  
        });
    }
    else if(e.which == 90) {    // 'z' - close all
        $('details').removeAttr('open');
    }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<details>
    <summary>Details1</summary>
    test1
    
    <details>
        <summary>Details2</summary>
    test2
    
        <details>
            <summary>Details3</summary>
    test3

        </details>
    </details>
</details>