菜单切换功能无法正常工作

时间:2014-02-17 16:57:15

标签: javascript html css

除了第一次调用tab_toggle(0)外,它始终正常工作 当第一次调用这个函数时,#box_home有display:block;所以函数不应该做任何事情,但是发生的事情是#box_port(下一个div)正在显示:block;与以前一样#box_home剩余display:block。为什么会发生这种情况。是因为当调用函数时,变量的值是未定义的,所以做一些随机的事情。 请在javascript中回答这个问题,不要在jquery中回答。 我不能让它在jsfiddle这个部分工作,所以我分享整个网页代码 http://goo.gl/dhTUDH

<!-- Javascript -->
<script>
function tab_toggle(x) {
    console.log("tab_toggle");
    var home    = document.getElementById("box_home").style;
    var port    = document.getElementById("box_port").style;
    var about   = document.getElementById("box_about").style;
    var contact = document.getElementById("box_contact").style;
    var box     = [home,port,about,contact];

switch (x) {
    case 0:
        if (home.display == "block") {
            console.log('end');
        } else if (port.display == "block") {
            box[0].display = "block";
            box[1].display = "none";
        } else if (about.display == "block") {
            box[1].display = "block";
            box[2].display = "none";
        } else {
            box[2].display = "block";
            box[3].display = "none";
        }
        break;
    default: 
        if (home.display == "block") {
            box[0].display = "none";
            box[1].display = "block";
        } else if (port.display == "block") {
            box[1].display = "none";
            box[2].display = "block";
        } else if (about.display == "block") {
            box[2].display = "none";
            box[3].display = "block";
        } else {}
        break;
    }
}

<!-- HTML -->
<a href="javascript:tab_toggle(0)">&#9664;</a>
<a href="javascript:tab_toggle(1)">&#9654;</a>
<div id="box_home"></div>
<div id="box_port"></div>
<div id="box_about"></div>
<div id="box_contact"></div>

<!-- CSS -->
#box_home{display:block;}\
#box_port{display:none;}
#box_about{display:none;}
#box_contact{display:none;}

3 个答案:

答案 0 :(得分:0)

您无法直接将样式作为属性访问,如

home.display

相反,请使用getComputedStyle()方法

getComputedStyle(home).display

答案 1 :(得分:0)

element.style将获得元素的内联样式。试试getComputedStyle或添加课程。

getComputedStyle(box[0]).getPropertyValue("display")

答案 2 :(得分:0)

不确定你会达到什么目标,但这应该有效:

 var currentElement = 0;

(tab_toggle = function (x) {
  var home = document.getElementById("box_home").style;
  var port = document.getElementById("box_port").style;
  var about = document.getElementById("box_about").style;
  var contact = document.getElementById("box_contact").style;
  var box = [home, port, about, contact];
  if (currentElement + x < 0 || currentElement + x > box.length - 1)
    return;

  currentElement += x;
  console.log("toggled " + currentElement);

  for (var i = 0; i < box.length; i++) {
    box[i].display = "none";
  }

  box[currentElement].display = "block";

})(0);