水平伸缩动画导航菜单实现详解
本章节分享一个简单的导航菜单实现过程,需要的朋友可以做一下参考。
当鼠标悬浮于导航菜单之上时候,菜单会出现水平伸缩效果。
代码实例如下:
<!DOCTYPE html> <html> <head> <meta charset=" utf-8"> <meta name="author" content="http://www.pipipi.net/" /> <title>前端教程网</title> <style type="text/css"> #con div { width: 100px; margin: 5px 0 5px 0; font-size: 9pt; height: 23px; color: white; } </style> <script> function $(e) { return document.getElementById(e); } function roulMenu(e, maxW, minW) { var divs = $(e).getElementsByTagName('div'); for (var index = 0; index < divs.length; index++) { (function (index) { var tims, timss; divs[index].onmouseover = function () { var self = this; clearInterval(timss); tims = setInterval(function () { if (self.offsetWidth < maxW) { self.style.width = self.offsetWidth + 5 + 'px'; } else { clearInterval(tims); } }, 10); } divs[index].onmouseout = function () { var self = this; clearInterval(tims); timss = setInterval(function () { if (self.offsetWidth > minW) { self.style.width = self.offsetWidth - 5 + 'px'; } else { clearInterval(timss); } }, 10); } })(index); } } window.onload = function () { roulMenu('con', 200, 100); } </script> </head> <body> <div id="con"> <div style="background-color:red">红色菜单</div> <div style="background-color:green">绿色菜单 </div> <div style="background-color:blue">蓝色</div> <div style="background-color:yellow">黄色</div> <div style="background-color:pink">这是什么色</div> <div style="background-color:orange">桔色</div> <div style="background-color:black">黑色超酷</div> </div> </body> </html>
上面的代码实现了动画效果,下面介绍一下它的实现过程。
一.代码注释:
(1).function $(e) {
return document.getElementById(e);
},返回id属性值为e的元素对象。
(2).function roulMenu(e, maxW, minW) {},第一个参数规定菜单父元素的id属性值,第二个参数规定菜单的最大宽度,第三个参数规定菜单的最小宽度。
(3).var divs = $(e).getElementsByTagName('div'),获取父元素下所有的div元素集合。
(4).for (var index = 0; index < divs.length; index++) ,遍历div集合中的么一个元素。
(5).(function (index) {})(index),通过闭包的方式来为元素注册事件处理函数。
(6).var tims, timss,声明两个变量用作定时器函数的标识。
(7).divs[index].onmouseover = function () {},为元素注册onmouseover事件处理函数。
(8).var self = this,把当前div元素的引用赋值给变量self。
(9).clearInterval(timss),停止上一个动画,防止鼠标连续悬浮于同一个菜单,造成定时器函数叠加执行。
(10).tims = setInterval(function () {
if (self.offsetWidth < maxW) {
self.style.width = self.offsetWidth + 5 + 'px';
}
else {
clearInterval(tims);
}
}, 10),通过定时器函数的方式设置元素的宽度。
二.相关阅读:
(1).getElementsByTagName()方法可以参阅document.getElementsByTagName()一章节。
(2).onmouseover事件可以参阅javascript mouseover事件一章节。
(3).clearInterval()可以参阅clearInterval()一章节。
(4).setInterval()可以参阅setInterval()一章节。
(5).offsetWidth可以参阅js offsetWidth一章节。
(6).onmouseout事件可以参阅javascript mouseout事件一章节。