仅使用Javascript滑出菜单

时间:2015-06-29 01:18:40

标签: javascript html css

我想通过仅使用Javascript点击按钮来创建滑出菜单。我知道有很多解决方案,但所有解决方案都使用jQuery。我想用Javascript独家编码。有人可以帮帮我吗?

HTML

<li class="menu"><a href="#about" id="mainmenu">Menu<span class="box-shadow-menu"></span></a>
    <ul class="sub" id="sub">
        <li><a href="#">Dashboard></a></li>
        <li><a href="#">My Profile</a></li>
        <li><a href="#">Settings</a></li>
        <li><a href="#">Help</a></li>
        <li><a href="#">About</a></li>
        <li><a href="#">Logout</a></li>
    </ul>
</li>

CSS

#sub
{
    color: #FFF;
    background-color: #662D91;
    display: none;
    position: fixed;
    top: 0;
    right: 0;
    border-left: 1px solid #000;
    height: 100%;
    width: 238px;
    padding: 15px 25px;
    margin: 0;
    z-index: 20;
}
#sub a
{
    display: block;
    font-size: 1.1em;
    color: #fff;
    padding: 15px 0;
    border-bottom: 1px solid rgba( 255, 255, 255, 0.05 );
}

它应该从右端向左滑动。当幻灯片出现时,菜单元素也应该出现。

1 个答案:

答案 0 :(得分:3)

你可以使用css过渡轻松完成,不需要jquery或任何其他库,甚至不需要通过javascript做动画。 我创建了一个滑入/退出子菜单的简单示例:http://jsfiddle.net/pisamce/97x76otx/ Javascript用于切换css类,动画由css完成。

&#13;
&#13;
var menubtn = document.getElementById('mainmenu');
var sub = document.getElementById('sub');
menubtn.addEventListener('click', function () {
    var closed = sub.className.indexOf('closed') !== -1;
    if (closed) {
        sub.className = sub.className.replace('closed', 'open');
    } else {
        sub.className = sub.className.replace('open', 'closed');
    }
});
&#13;
.sub {
    position: absolute;
}
.open {
    left:0;
    -webkit-transition: all 500ms cubic-bezier(0.680, 0, 0.265, 1);
    -webkit-transition: all 500ms cubic-bezier(0.680, -0.550, 0.265, 1.550);
    -moz-transition: all 500ms cubic-bezier(0.680, -0.550, 0.265, 1.550);
    -o-transition: all 500ms cubic-bezier(0.680, -0.550, 0.265, 1.550);
    transition: all 500ms cubic-bezier(0.680, -0.550, 0.265, 1.550);
}
.closed {
    left:-100%;
    -webkit-transition: all 500ms cubic-bezier(0.680, 0, 0.265, 1);
    -webkit-transition: all 500ms cubic-bezier(0.680, -0.550, 0.265, 1.550);
    -moz-transition: all 500ms cubic-bezier(0.680, -0.550, 0.265, 1.550);
    -o-transition: all 500ms cubic-bezier(0.680, -0.550, 0.265, 1.550);
    transition: all 500ms cubic-bezier(0.680, -0.550, 0.265, 1.550);
}
&#13;
<li class="menu"><a href="#about" id="mainmenu">Menu<span class="box-shadow-menu"></span></a> 
    </ul>
    <ul class="sub closed" id="sub">
        <li><a href="#">Dashboard</a>
        </li>
        <li><a href="#">My Profile</a>
        </li>
        <li><a href="#">Settings</a>
        </li>
        <li><a href="#">Help</a>
        </li>
        <li><a href="#">About</a>
        </li>
        <li><a href="#">Logout</a>
        </li>
    </ul>
</li>
&#13;
&#13;
&#13;