做好的手风琴效果如下,具体看代码:
html代码
Accordion level one
- first item
- second item
- third item
level one
- first item
- second item
- third item
level one
- first item
- second item
- third item
<script> <BR>var heads = document.querySelectorAll(".first-level"); <BR>function headClick(event){ <BR>var target = EventUtil.getTarget(event); <BR>toggleDisplay(target.parentNode.querySelector("ul")); <BR>} <BR>for(var i=0;i<heads.length;i++){ <BR>EventUtil.addHandler(heads[i], "click", headClick); <BR>} <br><br>window.onunload = function (){ <BR>for(var i=0;i<heads.length;i++){ <BR>EventUtil.removeHandler(heads[i], "click", headClick); <BR>} <BR>heads = null; <BR>} <BR></script>
common.js文件
var EventUtil = {
addHandler : function (element, type, handler) {
if (element.addEventListener) {
element.addEventListener(type, handler, false);
} else if (element.attachEvent) {
element.attachEvent("on" + type, handler);
} else {
element["on" + type] = handler;
}
},
removeHandler : function (element, type, handler) {
if (element.removeEventListener) {
element.removeEventListener(type, handler, false);
} else if (element.detachEvent) {
element.detachEvent("on" + type, handler);
} else {
element["on" + type] = null;
}
},
getEvent : function (event) {
return event || window.event;
},
getTarget : function (event) {
return event.target || event.srcElement;
}
}
var getStyle = function (el, style) {
if (el.currentStyle) {
style = style.replace(/\-(\w)/g, function (all, letter) {
return letter.toUpperCase();
});
var value = el.currentStyle[style];
return value;
} else {
return document.defaultView.getComputedStyle(el, null).getPropertyValue(style);
}
}
var toggleDisplay = function (element) {
var display = getStyle(element, "display");
if (display == "none") {
element.style.display = "block";
} else {
element.style.display = "none";
}
}