Live2d Test Env

jq方法写选项卡的基本原理以及三种方法

使用jq写选项卡,告别了繁琐的循环以及命名规范

基本原理:

    1.当某一个btn被选中时,将这个btn的背景颜色设为橘色,其余兄弟btn背景颜色设为空(none)

    2.如果子div与btn的索引相同,就将这个div显示而其他兄弟div隐藏

      1).css函数参数2的回调函数方法;

      2).原生get方法再转jq对象 再进行设置的方法

      3).当前div使用show()方法,其余兄弟div使用hide()方法

    关键字:get()  siblings()  show()  hide()  css()

html页:

  4个btn,4个div

 <div id="wrap">
        <button>btn1</button>
        <button>btn2</button>
        <button>btn3</button>
        <button>btn4</button>
        <div>1</div>
        <div>2</div>
        <div>3</div>
        <div>4</div>
    </div>

css页:

  大盒子当前无样式,在实际开发中需要指定其宽高;第一个btn背景色为橘黄色;第一个子项div显示,其余兄弟div隐藏

 #wrap div {
            width: 300px;
            height: 200px;
            border: 1px solid red;
            display: none;
        }
        
        #wrap div:nth-of-type(1) {
            display: block;
            /* 第一个子项div显示 */
        }
        
        #wrap button:nth-of-type(1) {
            background: orange;
            /* 第一个btn背景色为橘黄色; */
        }

  

jquery页:

1)首先给btn绑定事件

$("#wrap button").click(function() {
        //当btn被点击后发生的事件
})        

    关键字: click();

2) 当btn被点击时,设置当前选中btn颜色为橘色,并且将其他兄弟btn背景色为空:

$(this).css("background", "orange").siblings("button").css("background", "none")

    关键字:  $(this);  css();   siblings()

3) 声明一个变量,这个变量保存了被选中的btn的下标

var $index = $(this).index();

    关键字:$index; $(this);index();

 // 1:找到所有的子div,并且设置css样式,如果某个div的索引与btn的索引相同,就让他显示
                    $("#wrap div").css("display", function(i) {
                        if (i == $index) {
                            return "block";
                        }
                        return "none";
                    })

 

    关键字:css() ; "display" ; i == $index;

  b:通过get()方法将子div的索引与当前btn的索引绑定,然后再将这个索引转变成jq对象,再使用jq方法将对应div显示

$($("#wrap div").get($(this).index())).css("display", "block").siblings("div").css("display", "none")

    由于get方法是js原生方法,所以应将其转成jq对象才能使用jq方法

    关键字: $()  ; $(this).index; get();css();siblings()    

  c:通过当前btn的索引绑定div的索引,进而将这个索引对应的div显示show(),并将其余的div兄弟元素隐藏hide()

$("#wrap div").eq($(this).index()).show().siblings("div").hide();

    关键字:eq();$(this).index();show();hide()

  这样,就完成了使用jQuery方法实现选项卡。

  以上。

 

 

 

 

  

posted @ 2019-10-11 18:37  致爱丽丝  阅读(725)  评论(0编辑  收藏  举报