如何在HTML中创建下拉菜单

时间:2018-01-31 00:44:29

标签: html

我正在处理的作业要求创建一个下拉菜单,例如链接中的下拉菜单。我该怎么做?

enter image description here

2 个答案:

答案 0 :(得分:5)

你可以使用detailssummary HTML5元素(如果IE和Opera Mini不是一个大问题;对于那些下面的例子将优雅地回退)



<details>
  <summary>Please fill out our optional survey</summary>
  <p>What year are you in college?</p>
  <label><input type="radio" name="clg" value="0"> Not yet there</label>
  <label><input type="radio" name="clg" value="1"> Junior</label>
  <label><input type="radio" name="clg" value="2"> Senior</label>
</details>
&#13;
&#13;
&#13; https://developer.mozilla.org/en-US/docs/Web/HTML/Element/summary
http://html5doctor.com/the-details-and-summary-elements/

查找Toggle an element

的其他方法

要在JavaScript中重新创建以上内容,这是一个ES6示例:

&#13;
&#13;
[...document.querySelectorAll('[data-details]')].forEach( el => 
  el.addEventListener('click', () => {
    document.querySelector(el.getAttribute('data-details')).classList.toggle('hide');
    el.classList.toggle('open');
    el.setAttribute('aria-expanded', el.classList.contains('open'));
  })
);
&#13;
[data-details] {
  display: block;
  width: 100%;
  -webkit-appearance: none;
  background: none;
  border: none;
  text-align: left;
  font: inherit;
}
[data-details]:before      { content: "\25ba"; speak: none; }
[data-details].open:before { content: "\25bc"; speak: none; } 

.hide{ display: none; }
&#13;
<button type="button" data-details="#d1" aria-describedby="d1" aria-expanded="false" >Summary 1</button>
<div id="d1" class="hide">CONTENT ONE</div>

<button type="button" data-details="#d2" aria-describedby="d2" aria-expanded="false">Summary 2</button>
<div id="d2" class="hide">CONTENT TWO</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

正如另一个答案所指出的,您可以使用detailssummary元素,但它们支持得很差,仅在Chrome和Firefox中可用,如果您需要在IE中使用的解决方案,Edge和Safari一样,你需要使用javascript,谢天谢地,这很简单。

<div id="summary" onclick="toggle();">Summary</div>
<div id="togglable" style="display:none;">Toggleable text</div>

<script>
    var i=0;//Counter
    function toggle(){//Function called when Summary is clicked
        if(i%2===0){//Even number
            document.getElementById("toggle").style.display="initial";//Make it visible
        }else{//Odd number
            document.getElementById("toggle").style.display="none";//Visible
        }
        i++;
        if(i===2){
            i=0;//Reset i to ensure it doesn't get too big
        }
    }
</script>