javascript樹形導航選單例項程式碼

admin發表於2017-03-14

樹形選單在網頁中有著廣泛的應用,因為它能夠很好的組織起主次分類關係,同時也節省了網頁的空間,當然是先此種效果的方式有多重多樣,下面是用原生javascript實現的此效果,希望能夠對需要的朋友有所幫助。

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼
<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>js實現的樹形選單-螞蟻部落</title>
<style type="text/css">
.expand{
  cursor:pointer;
}
.hide{
  cursor:pointer;
}
</style>
<script type="text/javascript"> 
function toggleChild(o){ 
  var cls=o.getAttribute("class"); 
  if(cls == "expand"){ 
    var sb=o.nextSibling; 
    if(window.innerWidth) sb=sb.nextSibling; 
    while(sb!= null&&sb.tagName.toLowerCase()=='dd'){ 
      sb.style.display="none"; 
      sb=sb.nextSibling; 
      if(window.innerWidth) sb = sb.nextSibling; 
    } 
    o.removeAttribute("class"); 
    o.setAttribute("class", "hide"); 
    if(window.innerWidth) //ff 
    o.textContent = "田" + o.textContent.substring(1); 
    else 
    o.innerText = "田" + o.innerText.substring(1); 
  } 
  else{ 
    var sb = o.nextSibling; 
    if(window.innerWidth) sb = sb.nextSibling; 
    while (sb != null && sb.tagName.toLowerCase() == 'dd'){ 
      sb.style.display = ""; 
      sb = sb.nextSibling; 
      if(window.innerWidth) sb = sb.nextSibling; 
    } 
    o.removeAttribute("class"); 
    o.setAttribute("class", "expand"); 
    if(window.innerWidth) //ff 
    o.textContent = "曰" + o.textContent.substring(1); 
    else 
    o.innerText = "曰" + o.innerText.substring(1); 
  } 
} 
function maketree(obj){ 
  var dts=obj.getElementsByTagName('dt'); 
  var bro=navigator.userAgent; 
  for(var i=0;i<dts.length;i++){ 
    if(bro.indexOf("MSIE 6.0")>0|| bro.indexOf("MSIE 7.0")>0){
      dts[i].setAttribute("className", "expand");
    }
    else{
      dts[i].setAttribute("class","expand"); 
    }
    if(window.innerWidth)
      dts[i].textContent="曰"+dts[i].textContent; 
    else 
      dts[i].innerText="曰"+dts[i].innerText; 
    dts[i].onclick=function(){toggleChild(this);}; 
  } 
} 
window.onload=function(){ 
  maketree(document.getElementById("tree")); 
}; 
</script>
</head>
<body>
<h3>定義列表也能變成一棵樹:</h3>
<dl id="tree">
  <dt>選單一</dt>
  <dd>1.1 div教程</dd>
  <dd>1.2 css教程</dd>
  <dd>1.3 ccc</dd>
  <dt>選單二</dt>
  <dd>2.1 jQuery教程</dd>
  <dd>javascript教程</dd>
  <dt>選單三</dt>
  <dd>
    <dl style="margin-top:2px; margin-bottom:2px;">
      <dt>3.1</dt>
      <dd>螞蟻部落一</dd>
      <dd>螞蟻部落二</dd>
      <dt>3.2</dt>
      <dd>螞蟻部落三</dd>
      <dd>螞蟻部落四</dd>
    </dl>
  </dd>
</dl>
</body>
</html>

相關文章