最近做一个导航栏跟随效果的页面,于是写了个插件分享一下。
example.gifCSS 设置
.nav {
position: absolute;
top: 30px;
right: 100px;
display: inline-block;
margin: 20px auto;
}
.nav li {
display: inline-block;
margin-right: 20px;
}
.nav li a {
text-decoration: none;
color: #333;
}
.underline {
position: absolute;
top: 30px;
left: 0;
width: 32px;
height: 2px;
background: #333;
-webkit-transition: all .5s;
-moz-transition: all .5s;
-ms-transition: all .5s;
-o-transition: all .5s;
transition: all .5s;
}
HTML 结构
<ul class="nav">
<li><a href="javascript:;">首页</a></li>
<li><a href="javascript:;">产品中心</a></li>
<li><a href="javascript:;">关于我们</a></li>
<li><a href="javascript:;">联系我们</a></li>
<li class="underline"></li>
</ul>
Native 原生写法
// Native
(function () {
var nav = document.querySelector('.nav'),
underline = nav.querySelector('.underline');
nav.addEventListener('mouseover', function (event) {
var _target = event.target;
if (_target.nodeName == "LI" || _target.nodeName == "A") {
underline.style.left = _target.offsetLeft + 'px';
underline.style.width = _target.offsetWidth + 'px';
}
}, false);
})();
jQuery 写法
// jQuery
(function ($) {
var $nav = $('.nav'),
$underline = $nav.find('.underline');
$nav.on('mouseover', 'li', function() {
var _navOffsetLeft = $nav.offset().left,
_targetOffsetLeft = $(this).offset().left,
_targetWidth = $(this).width();
$underline.css({
'left': _targetOffsetLeft - _navOffsetLeft + 'px',
'width': _targetWidth + 'px'
});
});
})(jQuery);
另外我编写了插件放在Github上面(nav-nuderline.js), https://github.com/wwlsky/nav-nuderline/
网友评论