先上最终效果
需求分析:
1. 选项卡菜单数量不固定, 菜单内容不固定, 导致了单个菜单和整体的宽度都是未知的,
2. 第一个需求导致滑块宽度也是不固定的
3. 为了让交互效果更好, 滑块需要添加过度动画
对滑块的需求导致滑块和菜单的 html 结构必须分离, 并使用了 jQuery 的 offset 方法获取并设置位置, 所有的 div 都使用了相对定位.
本案例的 TAB 选项卡可以比较方便的拓展, 重复使用, 只需修改少量值就可以直接食用
水平有限不足之处欢迎指正
html 代码
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <title>0908</title>
- <script src="http://lib.sinaapp.com/js/jquery/1.7.2/jquery.min.js"></script>
- <style>
- /*container 容器只是为了水平居中, 如不需要可以去掉这层嵌套 */
- .container{
- left: 50%;
- margin-top: 100px;
- float: left;
- cursor:pointer;
- position: relative;
- }
- .BG{
- right: 50%;
- font-size: 0;
- background-color: #f2f2f2;
- border-radius: 30px;
- position: relative;
- }
- .container div{
- font-size: 16px;
- line-height: 60px;
- }
- .list{
- float: left;
- display: inline-block;
- padding: 0 50px;
- transition: color 0.5s;
- position: relative;
- z-index: 1;
- }
- /* 这里的 listH 和 listA 顺序不能换, 有优先级, 当 listA 被使用时 listH 不起作用 */
- .listH{
- color: #ff8300;
- }
- .listA{
- color: #fff;
- }
- /* 滑块 */
- #active{
- width: 100px;
- height: 60px;
- border-radius: 30px;
- background-color: #ff8300;
- box-shadow: 0 5px 16px 0 rgba(255, 144, 0, 0.58);
- position: relative;
- z-index: 0;
- transition: left 0.5s,width 1s;
- }
- </style>
- <script>
- $(document).ready(function () {
- /* 设置默认激活的选项卡 eq(i)*/
- var aL = $(".list:eq(1)");
- $("#active").width(aL.innerWidth());
- $("#active").offset(aL.offset());
- aL.addClass("listA");
- /* 为每个按钮添加点击事件 */
- $(".list").click(function() {
- $("#active").width($(this).innerWidth()); // 设置宽度
- $("#active").offset($(this).offset()); // 设置位置
- $(this).addClass("listA");
- $(".list").not(this).removeClass("listA");
- });
- /*hover 效果 */
- $(".list").hover(function () {
- $(this).addClass("listH")
- },function () {
- $(this).removeClass("listH")
- })
- });
- </script>
- </head>
- <body>
- <div class="container">
- <div class="BG">
- <div class="list">one</div>
- <div class="list">twotwo</div>
- <div class="list">threethreethree</div>
- <div class="list">four</div>
- <div class="list">fivefivefive</div>
- <div id="active"></div>
- </div>
- </div>
- </body>
- </html>
来源: http://www.qdfuns.com/article/46502/402e51efa653104b83074eb6212ff7d0.html