原生js做的手风琴效果的导航菜单_Javascript教程-查字典教程网
原生js做的手风琴效果的导航菜单
原生js做的手风琴效果的导航菜单
发布时间:2017-01-14 来源:查字典编辑
摘要:做好的手风琴效果如下,具体看代码:html代码复制代码代码如下:Accordion#accordion{width:200px;}#acco...

做好的手风琴效果如下,具体看代码:

html代码

复制代码 代码如下:

<!doctype html>

<html>

<head>

<meta charset="utf-8">

<title>Accordion</title>

<style>

#accordion{

width:200px;

}

#accordion ul{

list-style: none;

display:none;

}

.first-level{

background-color: #d8d8d8;

background-color: rgba(236, 208, 208, 0.53);

border-radius: 4px;

display: block;

cursor: pointer;

position: relative;

margin: 2px 0 0 0;

padding: 8px;

min-height: 0;

}

</style>

</head>

<body>

<div id="accordion">

<div>

<h3>level one</h3>

<ul>

<li>first item</li>

<li>second item</li>

<li>third item</li>

</ul>

</div>

<div>

<h3>level one</h3>

<ul>

<li>first item</li>

<li>second item</li>

<li>third item</li>

</ul>

</div>

<div>

<h3>level one</h3>

<ul>

<li>first item</li>

<li>second item</li>

<li>third item</li>

</ul>

</div>

</div>

<script src="common.js"></script>

<script>

var heads = document.querySelectorAll(".first-level");

function headClick(event){

var target = EventUtil.getTarget(event);

toggleDisplay(target.parentNode.querySelector("ul"));

}

for(var i=0;i<heads.length;i++){

EventUtil.addHandler(heads[i], "click", headClick);

}

window.onunload = function (){

for(var i=0;i<heads.length;i++){

EventUtil.removeHandler(heads[i], "click", headClick);

}

heads = null;

}

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";

}

}

相关阅读
推荐文章
猜你喜欢
附近的人在看
推荐阅读
拓展阅读
  • 大家都在看
  • 小编推荐
  • 猜你喜欢
  • 最新Javascript教程学习
    热门Javascript教程学习
    编程开发子分类