CSS3 + JS 导航栏鼠标跟随效果

最近做一个导航栏跟随效果的页面,于是写了个插件分享一下。
CSS3 + JS 导航栏鼠标跟随效果_第1张图片
example.gif

CSS 设置

.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 结构


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/

你可能感兴趣的:(CSS3 + JS 导航栏鼠标跟随效果)